Switch statements
JavaScript offers switch
/case
statements as an alternative to wordy repetitions of if
/else-if
. You provide a value to switch
, then attempt to match it against a series of patterns. The first matching block is executed. Unfortunately, JavaScript inherited its semantics from C, which comes with an unpleasant gotcha. If break
is not specified at the end of a block, the code will continue through and execute the body of the next block as well. While this can be used intentionally by clever programmers to string together complex logic, more often than not it is used by accident when someone forgets a break
. Let's take a look at an example:
switch (command) { case "build": compile(); break; case "deploy": activate(REMOTE_SERVER); start_ftp(); break; case "test": check_files(); run_test_suite(); case "NUKE": remove(ALL_THE_FILES); break; default: console.log("Unknown command"); }
What happens when someone passes "test"
there? Do...