Using multiple if statements or if else statements, look very bulky in JavaScript or other programming languages.
Multiple if statements and then else JavaScript Example
If condition matches then inside code execute of if and else. But if the condition matched the last if statement then else will not be executed.
<!DOCTYPE html>
<html>
<head>
<body>
<script type="text/javascript">
var a = 0;
if (a == 0) {
console.log("Green");
}
if (a == 1) {
console.log("Yellow");
}
if (a == 2) {
console.log("Red");
}
if (a == 3 ) {
console.log("Blue");
} else {
console.log("None");
}
</script>
</body>
</html>
Output:
An alternative to multiple if-else statements in JavaScript?
if-else Multiple
A much better solution is if-else compare to if multiple and last else condition statement. Else will be executed only if all conditions false.
<!DOCTYPE html>
<html>
<head>
<body>
<script type="text/javascript">
var a = 0;
if (a == 0) {
console.log("Green");
}
else if (a == 1) {
console.log("Yellow");
}
else if (a == 2) {
console.log("Red");
}
else if (a == 3 ) {
console.log("Blue");
} else {
console.log("None");
}
</script>
</body>
</html>
Output: This time output only “Green”.
Switch Case (Alternative)
Switch statements are the most obvious substitute for if statements.
Use the switch statement, which is better for times when there is a single variable you want to check against multiple possible values.
<!DOCTYPE html>
<html>
<head>
<body>
<script type="text/javascript">
var a = 1;
switch (a) {
case 0 :
console.log("Green");
break;
case 1:
console.log("Yellow");
break;
case 2:
console.log("Red");
break;
case 3:
console.log("Blue");
break;
default:
console.log("None");
break;
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestion on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
Even better than a switch statement, in simple cases like this would be to put the values into an array.
const colours = [
‘Green’,
‘Yellow’,
‘Red’,
‘Blue’
];
const selected colour = colours[a]
? colours[a]
: ‘None’;
console.log(selected colour);
This is easier and less error prone than using ifs or switch, and I would say that it’s easier to understand too.