JavaScript switch statement

JavaScript switch statement | syntax and examples

You will learn about the JavaScript switch statement in this tutorial.

The JavaScript switch statement is used to make decisions. The switch statement is used to perform various actions depending on different conditions.

It evaluates an expression and executes the body that corresponds to the result of the expression.

The switch statement has the following syntax:

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

The switch statement evaluates a variable or expression contained within parentheses ().

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 Statement

The break statement is optional. The switch statement is terminated if the break statement is encountered.
If no break statement is used, the cases following the matching case are executed as well.
The default clause is optional as well.

or in simple words,

When JavaScript meets a break keyword, it exits the switch block.

This will stop execution within the switch block.

Breaking the last case in a switch block is not required. In any case, the block breaks (ends) there.

The switch statement examples

Here is a simple example.

let value = 50;
switch (value) {

  case 30:
     value = "Thirty";
    break;

  case 40:
    value = "Fourty";
    break;

  case 50:
    value = "Fifty";
 
}
console.log(`The value is ${value}`);

//output: The value is Fifty

Here is an example with default keyword:

let value = 50;
switch (value) {

  case 0:
     value = "one";
    break;

  case 1:
    value = "two";
    break;

  case 2:
    value = "three";
    break;

  default:
    value = "value not available";
 
}
console.log(`${value}`);

//output: value not available

Switch statement for common conditions

Cases in a JavaScript switch statement can share the same code block.

// multiple case switch program
let lang = 'Java';
switch(lang) {
    case 'JavaScript':
    case 'Go':
    case 'Java':
        console.log(`${lang} is a programming language.`);
        break;
    default:
        console.log(`${lang} is a general language.`);
        break;
}

//output: Java is a programming language.

Multiple cases are grouped in the above example. The code for all of the grouped cases is the same.

The output is the same if the lang variable is set to Javascript, Go, or Java.

Read More: JavaScript Errors Try Catch Throw

AdBlocker Message

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.