Javascript Switch

The switch statement is used to represent various actions based on different conditions. It can replace multiple if checks and gives a more descriptive way for comparing a value with multiple variant.

To perform a multiway branch, you can use multiple else…if statements, as in the previous chapter, but it is not the best way. It is better to use a switch statement which is more efficiently than repeated else if statements.

Syntax

The main objective of a switch is to give an expression for evaluating and many various statements for executing. Both objectives are based on the value of the expression. The interpreter is checking each case against the value of the expression until it founds a match. If nothing matches, there will be used a default condition.

The switch statement has one or more case blocks and an optional default, which looks like this:

switch (x) {
  case 'value1': // if (x === 'value1')
    ...[
      break
    ]
  case 'value2': // if (x === 'value2')
    ...[
      break
    ]
  default:
    ...[
      break
    ]
}
  • The value of x is checked for an equality of a strict to the value from the first case, it is value2, then to the second value2 and so on.
  • If the equality is found, switch executes the code starting from the analogous case, until the end of switch.
  • If nothing matched, the default code will be used.

Example of the switch:

let a = 2 * 3;
switch (a) {
  case 3:
    console.log('Too small');
    break;
  case 6:
    console.log('Exactly!');
    break;
  case 8:
    console.log('Too large');
    break;
  default:
    console.log("I don't know such values");
}

The switch compares a from the 3 which is the first case variant, the match fails.

Then 6 that is a match, it means that the execution starts from case 6 until the nearest break.

If there is no break the execution will continue with the next case without any checks.

Example of the switch without break:

let a = 2 * 3;
switch (a) {
  case 3:
    console.log('Too small');
  case 6:
    console.log('Exactly!');
  case 8:
    console.log('Too big');
  default:
    console.log("I don't know such values");
}

There are sequential execution of three console.logs in the example above:

console.log('Exactly!');
console.log('Too big');
console.log("I don't know such values");

When JavaScript meets a break keyword, it breaks out of the switch block. That stops the execution of inside the block.

It is not important to break the last case in a switch block, the block breaks there anyway.

If you forget a break the program continues execution at the next statement in the switch statement, even if the evaluation does not match the case.

The default keyword defines the code to run if there is no case match.

Any expression can be a switch/case argument. Both switch and case allow random expressions.
let a = "4";
let b = 2;
switch (+a) {
  case b * 2:
    console.log("this runs, because +a is 4, exactly equals b*2");
    break;
  default:
    console.log("this doesn't run");
}

The examples shows that +a gives 4, that’s compared with b * 2 in case, and the corresponding code is implemented.

Grouping of “case”

If several variants of case share the same code they can be grouped. So if we want the same code to run for case 2 and case 3 or case 5, case 6 and case 8 we do this:

let val;
let answer = "";
switch (val) {
  case 1:
    answer = "Low";
    break;
  case 2: // (**) 
  case 5:
    answer = "Mid";
    break;
  case 3:
  case 6:
  case 8:
    answer = "High";
    break;
  default:
    answer = "Massive?";
}

At the result both 2 and 5 cases and 3, 6 , 8 cases show the same message.

The ability to “group” cases is an aftereffect of how switch/case works without break. The execution of case 2 starts from the line (**), then it goes through case 5, because there’s no break.

Type matters

Let’s focus attention on the equality check that is always strict. The values here must be of the same type to match.

Example of the type matters:

let arg = prompt("Guess the car?");
switch (arg) {
  case 'bmw':
    console.log('BMW');
    break;
  case 'mercedes':
    console.log('Mercedes');
    break;
  default:
    console.log('An unknown value');
}

As you see the first alert runs for bmw, the second alert runs for mercedes.




Do you find this helpful?

Related articles