JavaScriptLesson 4 of 10Jump to practice

Conditions

Run different code depending on a condition with if, else if and else.

Programs make decisions. Conditions let your code take one path or another.

if

if (condition) {
  // runs only when the condition is true
}

if and else

Open or closed?
Open in editor
<script>
const hour = new Date().getHours();

if (hour >= 9 && hour < 17) {
  console.log("The shop is open.");
} else {
  console.log("Sorry, we're closed. Open 9am to 5pm.");
}
console.log("It is now hour", hour);
</script>
Result

else if: more than two choices

Chain conditions with else if. JavaScript checks them in order and runs the first one that’s true.

Exam grade
Open in editor
<script>
const marks = 74;
let grade;

if (marks >= 80) {
  grade = "A+";
} else if (marks >= 70) {
  grade = "A";
} else if (marks >= 60) {
  grade = "A-";
} else if (marks >= 50) {
  grade = "B";
} else if (marks >= 40) {
  grade = "C";
} else if (marks >= 33) {
  grade = "D";
} else {
  grade = "F";
}

console.log(marks + " marks is grade " + grade);
</script>
Result

Change marks and run it again. Then try moving the marks >= 40 check to the top. Every passing mark becomes a C, because the first true condition wins. Order matters.

True-ish and false-ish values

A condition doesn’t have to be a comparison. JavaScript treats some values as false:

false, 0, "" (an empty string), null, undefined and NaN.

Everything else counts as true. That gives a handy check for an empty input:

const name = "";
if (name) {
  console.log("Hello " + name);
} else {
  console.log("Please type your name");
}

The short form

For a simple either-or value, the ternary operator fits on one line:

const label = age >= 18 ? "Adult" : "Child";

Read it as: is age at least 18? If so, “Adult”, otherwise “Child”. Keep it for short choices. For anything bigger, if is easier to read.

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Run the message only when the temperature is above 30.

     (temperature > 30) {
      console.log("Hot day");
    }

  2. Exercise 2

    Run the second block when the condition is false.

    if (isLoggedIn) {
      console.log("Welcome back");
    }  {
      console.log("Please log in");
    }

  3. Exercise 3

    Check a second condition when the first one is false.

    if (marks >= 80) {
      grade = "A+";
    }  (marks >= 70) {
      grade = "A";
    }

Quiz: 3 questions

1. In an if / else if / else chain, how many blocks run?
2. What runs when no condition is true and there is no else?
3. Which value counts as false in a condition?

Finish the practice to complete this lesson.

Sign in to keep your progress on any device.