JavaScript Statement: switch {case … case
… default …}
[this page | pdf | back links]
In JavaScript,
the switch statement marks a
block of statements to be executed depending on different cases that an
expression provided with the switch
statement takes. The statement takes e.g. the following format:
var x;
switch(expression)
{
case 1:
x = 10;
break;
case 3:
x = 20;
break;
default:
x = 5;
}
In the above the expression
would be evaluated. If its value was 1
then the code following the case 1
statement would be executed, if it was 2
then the code following the case 3
statement would be executed, and if it was neither then the code immediately
after the (optional) default
statement would be executed.
The format of this
statement differs from e.g. the select
… case … case else statement in Visual Basic. The VB select statement results in only the
code immediately following the relevant case
or case else statement being
executed. In contrast, with JavaScript, all the code from the relevant case statement to the end of the switch expression block is executed,
until a break statement is
reached. So, in the above, if the first break statement was commented out then x would become 20 if expression was either 1 or 3 (if
it was one then it would be set to 10
but then subsequently set to 20).
If expression
evaluates to a Boolean (i.e. true or false) then it is more common to use the if (or variants
such as if … else)
statement.
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
function crSp(n) { return '<br>' + (' ').repeat(n) }
var x;
switch(3) {
case 1:
x = 10;
break;
case 3:
x = 20;
break;
default:
x = 5;
}
document.getElementById("Example").innerHTML =
'var x;'
+ crSp(0) + 'switch(3) {'
+ crSp(2) + 'case 1:'
+ crSp(4) + 'x = 10;'
+ crSp(4) + 'break;'
+ crSp(2) + 'case 3:'
+ crSp(4) + 'x = 20;'
+ crSp(4) + 'break;'
+ crSp(2) + 'default:'
+ crSp(4) + 'x = 5;'
+ crSp(0) + '}';
document.getElementById("Result").innerHTML = x;
</script>
</body>
</html>
|
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words