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

if...else statements

 

Let's look at by far the most common type of conditional statement you'll use in JavaScript — the humble if...else statement.

Basic if ... else syntax

Basic if...else syntax looks like the following in pseudocode:

if (condition) { code to run if condition is true } else { run some other code instead }

Here we've got:

  1. The keyword if followed by some parentheses.
  2. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). The condition makes use of the comparison operators we discussed in the last module and returns true or false.
  3. A set of curly braces, inside which we have some code — this can be any code we like, and it only runs if the condition returns true.
  4. The keyword else.
  5. Another set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false.

This code is pretty human-readable — it is saying "if the condition returns true, run code A, else run code B"

You should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code:

if (condition) { code to run if condition is true } run some other code

However, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition returns true or false. This is not necessarily a bad thing, but it might not be what you want — often you want to run one block of code or the other, not both.

As a final point, you may sometimes see if...else statements written without the curly braces, in the following shorthand style:

if (condition) code to run if condition is true else run some other code instead

This is perfectly valid code, but using it is not recommended — it is much easier to read the code and work out what is going on if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation.