JavaScript Switch Statement


switch statement helps to do different things depending on different situations.

The JavaScript Switch Statement

Sure, here is the simplified version: Use the switch command to choose one of various code blocks for execution.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

The break Keyword

When JavaScript encounters a 'break' keyword within a switch block, it exits the block.

This will halt the process within the switch block.

Breaking the final case in a switch block is not mandatory. The block naturally concludes at that point.

Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.


The default Keyword

The default keyword indicates the code to execute when no matching case is found.

The default case in a switch block doesn't necessarily need to be the last one.

If the word default is not the final option in the switch block, ensure to conclude the default choice with a break statement.


Common Code Blocks

At times, you may need various switch cases to utilize identical code.

In this instance, code blocks 4 and 5 have identical content, while code blocks 0 and 6 share a different set of code.


Switching Details

If several situations match a particular case value, the first case encountered is chosen.

If the program doesn't find any matching cases, it moves on to the default label.

If the program doesn't find a default label, it proceeds to the statement(s) following the switch.


Strict Comparison

Switch cases employ strict comparison (===).

The values must be of the same type to match.

A direct comparison is only accurate when the items being compared are of identical types.

In this example there will be no match for x: