To execute a single block of code satisfying a condition in case
statement of JavaScript switch-case
is used. break
keyword is used in every case
statement to exit the switch
statement so that it should not enter into other case
clause statement.
Syntax
switch (expression) { case value1: // code block to be executed when expression result matches value1; [break;] case value2: // code block to be executed when expression result matches value2; [break;] ... case valueN: // code block to be executed when expression result matches valueN; [break;] [default: // code block to be executed when expression result doesn't match any of the values. [break;]] }
expression: an expression whose result is matched in each switch case
clause.
case valueN: a case clause keeps on matching the result of expression with each case
clause until it matches the value. It executes the code statements where the case value matches until either it reaches the end of the switch
statement block or a break
.
default: the code statements inside the default
clause are executed if expression result doesn’t match any of the case
clauses.
Usually break
is not required in default case
as it automatically exits after default
.
Example
var n; n = (Math.random() * 10); n = Math.ceil(n); switch(n) { case 5: document.write('Random Number is 5'); break; case 6: document.write('Random Number is 6'); break; case 7: document.write('Random Number is 7'); break; case 8: document.write('Random Number is 8'); break; case 9: document.write('Random Number is 9'); break; case 10: document.write('Random Number is 10'); break; default: document.write('Random Number is less than 5'); }
Above example is a code for a simple JavaScript game to trace the random number greater than 5 using JavaScript switch-case
statements.