• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

6.5. 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:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint