Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Switch

The switch statement is used to execute different actions based on various conditions.

The JavaScript Switch Statement

Use the switch statement to choose one of several code blocks to execute.

Syntax

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

Here’s how it works:

  1. The switch expression is evaluated once.
  2. The expression’s value is compared against the values of each case.
  3. If a match is found, the corresponding block of code is executed.
  4. If there is no match, the default block of code is executed.

Example

The getDay() method returns the day of the week as a number from 0 to 6.

(Sunday = 0, Monday = 1, Tuesday = 2, etc.)

This example uses the weekday number to determine the name of the day.

switch (new Date().getDay()) {
  case 0:
    day = “Sunday”;
    break;
  case 1:
    day = “Monday”;
    break;
  case 2:
     day = “Tuesday”;
    break;
  case 3:
    day = “Wednesday”;
    break;
  case 4:
    day = “Thursday”;
    break;
  case 5:
    day = “Friday”;
    break;
  case 6:
    day = “Saturday”;
}

The resulting day will be:

Wednesday