Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

switch

An if statement causes a branch in the flow of a program’s execution. You can use multiple if statements, as in the previous section, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. In this case, it is wasteful to repeatedly check the value of the same variable in multiple if statements.

The switch statement (implemented in JavaScript 1.2 and standardized by ECMAScript v3) handles exactly this situation, and it does so more efficiently than repeated if statements. The JavaScript switch statement is quite similar to the switch statement in Java or C. The switch keyword is followed by an expression and a block of code, much like the if statement:

switch(expression) {
    statements
}

However, the full syntax of a switch statement is more complex than this. Various locations in the block of code are labeled with the case keyword followed by a value and a colon. When a switch executes, it computes the value of expression and then looks for a case label that matches that value. If it finds one, it starts executing the block of code at the first statement following the case label. If it does not find a case label with a matching value, it starts execution at the first statement following a special-case default: label. Or, if there is no default: label, it skips the block of code altogether.

switch is a confusing statement to explain; its operation becomes much clearer with ...

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: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata