Switch

If you find yourself using an if condition and having too many else if parts, you could consider changing the if to a switch:

var a = '1',
    result = '';
switch (a) {
case 1:
  result = 'Number 1';
  break;
case '1':
  result = 'String 1';
  break;
default:
  result = 'I don\'t know';
  break;
}

The result after executing this is "String 1". Let's see what the parts of a switch are:

  • The switch statement.
  • An expression in parentheses. The expression most often contains a variable, but can be anything that returns a value.
  • A number of case blocks enclosed in curly brackets.
  • Each case statement is followed by an expression. The result of the expression is compared to the expression found after the switch statement. If the result of the comparison is true, the ...

Get Object-Oriented JavaScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.