Switch Statement
Using if statement over and over again can be harder to read especially when you write large amount of conditional statement. Sometimes we want to use switch statement.
var a = 10;
switch (a) {
case 0 :
alert("the number is 0");
case 10 :
alert("the number is 10");
case 100 :
alert("the number is 100");
default :
alert("that's not valid number");
}
In the example above, we want to check variable 'a'. If 0, then print "the number is 0". If 10, then print "the number is 10" and so on. If your variable is not one of the case, the default will be executed, in this case is alerting "that's not valid number".
But in the switch statement, there are something called fallthrough. In the example before, you can see variable a is 10, so our code will printing "the number is 10". But because of fallthrough, all statement after that will still get executed. That means our code will also printing "the number is 10" and "that's not valid number".
That's why in switch statement, we have to ending each case with word 'break'.
var a = 10;
switch (a) {
case 0 :
alert("the number is 0");
break;
case 10 :
alert("the number is 10");
break;
case 100 :
alert("the number is 100");
break;
default :
alert("that's not valid number");
}