Course Review

Congratulations! You've finished the course and have mastered the beginning concepts. We've covered a lot of material, and now it's time for two final practice exercises where you will see how to use JavaScript to solve real-world problems. The first exercise reviews "assignment", "declaration", and "conditional statements" like if/else and switch, and "comparison" and "logical" operators using interactive examples.

Final Practice Exercise Review

switch statements

 

if...else statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (for example, multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices.

In such a case, switch statements are your friend — they take a single expression/value as an input, and then look through a number of choices until they find one that matches that value, executing the corresponding code that goes along with it. Here's some more pseudocode, to give you an idea:

switch (expression) { case choice1: run this code break; case choice2: run this code instead break; // include as many cases as you like default: actually, just run this code }

Here we've got:

  1. The keyword switch, followed by a set of parentheses.
  2. An expression or value inside the parentheses.
  3. The keyword case, followed by a choice that the expression/value could be, followed by a colon.
  4. Some code to run if the choice matches the expression.
  5. break statement, followed by a semi-colon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.
  6. As many other cases (bullets 3–5) as you like.
  7. The keyword default, followed by exactly the same code pattern as one of the cases (bullets 3–5), except that default does not have a choice after it, and you don't need to break statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.

Note: You don't have to include the default section — you can safely omit it if there is no chance that the expression could end up equaling an unknown value. If there is a chance of this, however, you need to include it to handle unknown cases.