Core JavaScript

Switch Statements

Switch statements define blocks of code that get executed depending on the value of a variable. Below, there is a switch statement that branches the execution based the value of iN. There are case statements for the values 0, 1, 2, and 3. The default branch is executed for any other value.

Note that there is break statement inside of the case blocks. The break statement breaks out of the entire switch when it is executed. This ensures that only one block is executed. We can eliminate the break to allow more than one value to be used to select the same block of code. This is what has been done for the cases 2 and 3.

SwitchStatements.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="SwitchStatements.js"></script>
</body>
</html>

SwitchStatements.js

var iN = 2;

switch (iN) {
	case 0:
	{
		document.writeln("iN = 0<br />");
		break;
	}
	case 1:
	{
		document.writeln("iN = 1<br />");
		break;
	}
	case 2:
	case 3:
	{
		document.writeln("iN = 2 or 3<br />");
		break;
	}
	default:
	{
		document.writeln("iN = Something else<br />");
		break;
	}
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.