Sample Video Frame

Created by Zed A. Shaw Updated 2024-12-10 18:57:40
 

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:

  1. An if-statement like this simply performs the tests in (..), and if the test is true, then it runs the code in the {..} after.
  2. If the test is false, then it jumps to the next else if and performs that test.
  3. If that test is true it runs the {..}, otherwise it jumps to the next else if.
  4. When it has run out of else if clauses, the if-statement finally runs the code in the {..} after the else clause. Remember that the else only runs if all of the previous parts are false.
Previous Lesson Next Lesson

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.