Trusted answers to developer questions

How to use the switch statement in JavaScript

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The switch statement is used to control the flow of a program and is a part of JavaScript’s conditional statements. It allows the execution of a specific code block depending upon the evaluation of an expression.

The structure of switch

  • The switch structure starts with the switch keyword followed by the expression to be evaluated in parentheses.
switch (expression){
}
  • Inside the curly braces different cases are defined followed by a value to be strictly matched with the evaluated expression.
switch (expression){
case value1:
/* implement the statement(s) to be executed when
      expression = value1 */
break;
case value2:
/* implement the statement(s) to be executed when
      expression = value2 */
break;
case value3:
/* implement the statement(s) to be executed when
      expression = value3 */
break;
default:
/* implement the statement(s) to be executed if expression
     doesn't match any of the above cases */
}
  • The break statement is used to exit the switch structure after the execution of a case. If it is not used, all the subsequent cases will be executed until the program encounters any break statement or the ending curly brace } of the structure.

  • The default: is a special type of case and is executed when none of the cases match the evaluated expression.

Example

The program will find out the day of the week based on the value of the day variable.

Let’s look at the flow chart of this example for a better understanding:

Let’s look at the implementation of the example:

var day = 2; //change and try with different values
switch(day)
{
case 1: //if day = 1
console.log("Monday");
break;
case 2: //if day = 2
console.log("Tuesday");
break;
case 3: //if day = 3
console.log("Wednesday");
break;
case 4: //if day = 4
console.log("Thursday");
break;
case 5: //if day = 5
console.log("Friday");
case 6: //if day = 6
console.log("Saturday");
case 7: //if day = 7
console.log("Sunday");
break;
default: //if day doesn't match any of above
console.log("Invalid");
}

RELATED TAGS

javascript
switch
conditionals
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?