techStackGuru

JavaScript Switch Statement


The JavaScript switch statement is used to run one code from many expressions.

Each case values are compared to the expressions value. If a match is found, the code block linked with it will be called. The default code block is performed if there is no match.

switch-case-image

Syntax for switch case


switch(expression) {
    case one:
      // code 
      break;
    case two:
      // code 
      break;
    default:
      // code 
  }

Lets take an example of switch case by passing user name


const name = 'aura';
switch (name) {
  case 'vishal':
    alert('Hello vishal');
    break;
  case 'aura':
    alert('Hello aura');
    break;
  default:
    alert('Hello user');
}

previous-button
next-button