Skip to Content
JavaScript : Object-Oriented Programming
book

JavaScript : Object-Oriented Programming

by Kumar Chetan Sharma et al
August 2016
Beginner to intermediate
847 pages
17h 28m
English
Packt Publishing
Content preview from JavaScript : Object-Oriented Programming

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: Functional Programming for JavaScript Developers

JavaScript: Functional Programming for JavaScript Developers

Ved Antani, Simon Timms, Dan Mantyla
Mastering JavaScript Object-Oriented Programming

Mastering JavaScript Object-Oriented Programming

Andrea Chiarelli, Lyubomyr Rudko

Publisher Resources

ISBN: 9781787123595Supplemental Content