Sample Video Frame
15: If and Else
You already learned about jumps in Exercise 11 where you wrote a function that caused your code to jump to the top of the function, and then return to where you called the function. If you don't remember this then please go back to Exercise 11 and study it again because we are going to use the concept of jumping in your code to explain an if-statement
. Before you can learn about if-statements
you must first learn about "testing", which involves comparing two values or variables to get a true
or false
answer.
If-Statements
The easiest way to talk about if-statements
is to show you a small snippet of code and then show you how that relates to testing and jumps:
if (x === 10) {
// first jump
} else if (x < 10) {
// second jump
} else {
// last jump
}
Here's how this code works:
- An
if-statement
like this simply performs the tests in(..)
, and if the test istrue
, then it runs the code in the{..}
after. - If the test is
false
, then it jumps to the nextelse if
and performs that test. - If that test is
true
it runs the{..}
, otherwise it jumps to the nextelse if
. - When it has run out of
else if
clauses, theif-statement
finally runs the code in the{..}
after theelse
clause. Remember that theelse
only runs if all of the previous parts arefalse
.
Register for Learn JavaScript the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.