HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Switch Statement

The switch statement in JavaScript is used to perform different actions based on different conditions.
It evaluates an expression, matches the expression's value to a case clause, and executes the statements associated with that case.

Syntax

switch (expression) {
  case value1:
    // Statements to execute if expression === value1
    break;
  case value2:
    // Statements to execute if expression === value2
    break;
  // Additional cases...
  default:
    // Statements to execute if expression does not match any case
}
             

Example

let day = 2;
let dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day";
}

console.log("Today is " + dayName);

             

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

The default Keyword

In JavaScript, the default keyword is used in conjunction with the switch statement.
It specifies the code to run if none of the case values in the switch statement match the value of the expression being evaluated.