JAVASCRIPT SWITCH
JavaScript switch statement can be used to execute tasks based on specific conditions. When switch expression is evaluated, the matching case value’s code is executed. If no match is found, the default code is executed.
Syntax of JavaScript Switch Statement:
switch(expression) {
case x:
// code on case x
break;
case y:
// code on case y
break;
default:
// code executed if no case works
}
In the above code, the JavaScript break keyword is used to stop execution of the switch block there and move out of it. No break keyword is used for the last case as the switch statement ends there.
For switch statements, the case must fulfill strict comparison i.e., both value and type will be compared.
let num = 0;
switch (num) {
case 0: //this case code will be executed
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
Live Demo!