JavaScript Switch Statement

The switch statement can be used to perform multiple if statement functionality. It is used to perform various actions based on various conditions. The switch statement is used to select one of many code blocks to be executed. Its syntax is given below:

Switch Statement – Flowchart

The flowchart of the switch statement is given below:

JavaScript Switch Statement

Let’s understand this with an example:

<html>
<body>

<script>
let x = 5;
switch (x) {
  case 3:
    document.write( 'small' );
    break;
  case 4:
    document.write( 'Equal' );
    break;
  case 5:
    document.write( 'Big' );
    break;
  default:
    document.write( "I don't know such values" );
}
</script>

</body>
</html>

Output:

image 123

When the JavaScript comes on the break keyword, automatically it breaks out the switch block. The operation will stop the execution inside the switch block. It is not mandatory part to break the last case in a switch block. The block breaks there anyway.

The default case

If there is no case match, the default keyword allows the code to run.

<html>
<body>

<script>
let x = 8;
switch (x) {
  case 3:
    document.write( 'small' );
    break;
  case 4:
    document.write( 'Equal' );
    break;
  case 5:
    document.write( 'Big' );
    break;
  default:
    document.write( "I don't know such values" );
}
</script>

</body>
</html>

Output:

image 14

It is not necessary that the default block is the last block. You can put it anywhere and end with a break statement.

The first case will be selected if the several cases match a case value. The program continues to the default label, in case there are no cases found. The program continues to the statement after the switch if no default label is found.

Strict Comparison

Strict comparison (===) is used in switch cases.

The values must be the same type of match.

If the operands are of the same type the strict comparison can only be true Below is the example where no match for x is available: