+ 1
You can achieve the same result with multiple if...else statements, but the switch statement is more effective in such situation
Why is a switch statement more effective than multiple if else statements? Can someone explain with a simple example?
1 ответ
+ 4
We have to code less with switch statement. It makes our code simple and easier than if else statement.
Example: we have to check a number is either 1 or 2 or 3 or 0.
In if..else statement -->
var number = 0;
if(number == 0){
alert("0");
}else if(number == 1){
alert("1");
}else if(number == 2){
alert("2");
}else if(number == 3){
alert("3");
}
But in switch statement-->
var number = 0;
switch (number) {
case 0:
alert("0");
break;
case 1:
alert("1");
break;
case 2:
alert("2");
break;
case 3:
alert("3");
break;
}
Hope this will help you .