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:
- The keyword
if
followed by some parentheses. - 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
orfalse
. - 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
. - The keyword
else
. - 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 isfalse
.
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.