What is JavaScript Switch Statement?
JavaScript switch statement is a conditional statement used to execute one code from more than one expressions. The only difference between switch and if...else...if is that is more convenient. It can be used with characters, numbers e.t.c.
The syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Result: B Grade
What is the use of break in switch case statement?
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break statement. Let’s understand the use of break in switch statement in JavaScript. The break statement will help to stop the execution of the next block of code once a condition is met.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
Output of the above example
Result: undefined B Grade C Grade No Grade