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
.
The Code
Now that you have an idea of how an if-statement
works you can type in this code and play with it:
let x = 20;
if (x === 10) {
console.log("x is equal to 10:", x);
} else if (x < 10) {
console.log("x is less than 10:", x);
} else {
console.log("x is greater than 10:", x);
}
// consider this part a puzzle to solve
// what's the least number of times you have to change
// the code to make each console.log run?
let y = 100;
if (y == 100) {
if(x < 10) {
console.log("log 1", x, y);
} else {
console.log("log 2", x, y);
}
} else {
if(x > 10) {
console.log("log 3", x, y);
} else {
console.log("log 4", x, y);
}
}
You'll see that there's a little puzzle in the second half where I've created a complicated if-statement
with an if-statement
inside. You should try to solve the puzzle, but be warned that I mean for you to edit this file multiple times to get each console.log
to run. It's not possible to set x
and y
in a way that would cause all branches of those if-statements
to run.
What You Should See
You should change this code to change the variables and see how that changes the output. With the code as it is above the output should be:
$ node "code.js"
x is greater than 10: 20
log 2 20 100
Learn JavaScript Today
Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.
Still Not Sure? Try the next FREE Lesson!