Conditionals

In addition to the if statement we introduced briefly in Chapter 1, JavaScript provides a few other conditionals mechanisms that we should take a look at.

Sometimes you may find yourself writing a series of if..else..if statements like this:

  1. if (a == 2) {
  2. // do something
  3. }
  4. else if (a == 10) {
  5. // do another thing
  6. }
  7. else if (a == 42) {
  8. // do yet another thing
  9. }
  10. else {
  11. // fallback to here
  12. }

This structure works, but it’s a little verbose because you need to specify the a test for each case. Here’s another option, the switch statement:

  1. switch (a) {
  2. case 2:
  3. // do something
  4. break;
  5. case 10:
  6. // do another thing
  7. break;
  8. case 42:
  9. // do yet another thing
  10. break;
  11. default:
  12. // fallback to here
  13. }

The break is important if you want only the statement(s) in one case to run. If you omit break from a case, and that case matches or runs, execution will continue with the next case‘s statements regardless of that case matching. This so called “fall through” is sometimes useful/desired:

  1. switch (a) {
  2. case 2:
  3. case 10:
  4. // some cool stuff
  5. break;
  6. case 42:
  7. // other stuff
  8. break;
  9. default:
  10. // fallback
  11. }

Here, if a is either 2 or 10, it will execute the “some cool stuff” code statements.

Another form of conditional in JavaScript is the “conditional operator,” often called the “ternary operator.” It’s like a more concise form of a single if..else statement, such as:

  1. var a = 42;
  2. var b = (a > 41) ? "hello" : "world";
  3. // similar to:
  4. // if (a > 41) {
  5. // b = "hello";
  6. // }
  7. // else {
  8. // b = "world";
  9. // }

If the test expression (a > 41 here) evaluates as true, the first clause ("hello") results, otherwise the second clause ("world") results, and whatever the result is then gets assigned to b.

The conditional operator doesn’t have to be used in an assignment, but that’s definitely the most common usage.

Note: For more information about testing conditions and other patterns for switch and ? :, see the Types & Grammar title of this series.