The switch
statement is used to perform different actions based on different conditions. It is similar to if...else if
statement but switch statement is more convenient.
switch (expression) { case <expression 1>: <statement(s)> break; case <expression 2>: <statement(s)> break; ... ... case <expression n>: <statement(s)> break; default: statement(s) }
break
StatementIn order to separate each case. Javascript will run the statements of the first case that applies. Then upon the break statement it will leave the switch block and will not run the cases that follow.
default
LabelThe default label allows you to run a sequence of statements when none of the none cases corresponds to the test condition.
The example below assigns a character string that assigns a color to the marker variable according to the value of the color variable. If the value of color is unknown then this code will send message to the user.
var marker switch (color) { case 0: marker = "green"; break; case 1: marker = "green"; break; case 2: marker = "green"; break; default: document.write("Color is not referenced!"); }