JavaScript Code

JavaScript Switch-Case


Switch-Case Statement

switch (expression) {
  case a:
    //code
    break;
  case b:
    //code
    break;
  default:
    //code
}
  • switch is keyword
  • expression is any expression that evaluates to a values
  • case is keyword
  • a is value that the expression’s result would be matched against
  • b is value that the expression’s result would be matched against
  • code is any valid JavaScript code
  • break is the statement to break the switch-case statement

the expression is evaluated, and is compared with the case values. if there is a match, then the respective code block is executed. if there is no match, then the default block is executed

Examples

1. printing the number in text based on the number’s value

a = 2

switch (a) {
    case 0:
        console.log("zero");
        break;
    case 1:
        console.log("one");
        break;
    case 2:
        console.log("two");
        break;
    case 3:
        console.log("three");
        break;
    case 4:
        console.log("four");
        break;
    default:
        console.log("unknown number");
}