Switch statement

Using switch statement you can take a single variable value and execute a different block of code based on the value of the variable.

switch (NumberOne)

Instead of one variable you can have an addition of variables or any other sort of calculations.
Below you can see how a full switch statement looks like.

var NumberOne = 4;
switch (NumberOne) {
   case 6:
     document.write("6 is better than 4");
   case 2:
     document.write("2 is worst than 4");
     document.write("None of the cases are true");

The switch statement begins based on the NumberOne variable.
Next, a case is given (when the value of the variable NumberOne is 6) with the code to be executed if it is true.
The break statement after the first case tells the browser to leave the switch case block.
After that we have another case with another code to be executed if the case turns to be true and another break statement.
Finally, the default statement is used when none of the cases is true.

Leave a Reply