Complete JavaScript Course Module 3: Beginner: Making Decisions with Conditions

JavaScript if, else and else if Statements

  • Beginner
  • Lesson 3.1
  • 5 min read
  • 11 of 76 in the course

In short

JavaScript if statements let your code make decisions: do one thing when a condition is true and something else when it is false. Learn if, else, else if and comparison operators. What is an if statement?

JavaScript if statements let your code make decisions: do one thing when a condition is true and something else when it is false. Learn if, else, else if and comparison operators.

What is an if statement?

Every day you make decisions based on conditions: if it is raining, take an umbrella; otherwise, wear sunglasses. Programs need to make decisions too. An if statement runs a block of code only when a condition is true.

A condition is a question with a yes/no answer, like "Is the user older than 18?" In JavaScript, the answer is a boolean: true or false.

Comparison operators in JavaScript

To build conditions, you compare values with comparison operators. Each one gives back true or false.

OperatorMeaningExampleResult
===Equal to (same value and type)5 === 5true
!==Not equal to5 !== 3true
>Greater than10 > 7true
<Less than10 < 7false
>=Greater than or equal to18 >= 18true
<=Less than or equal to4 <= 3false

As you saw in the Type Conversion lesson, always use === and !== instead of == and !=.

if and else: a simple age check

Here is the basic shape of an if statement:

const age = 16;

if (age >= 18) {
  console.log('Welcome! You can create an account.');
} else {
  console.log('Sorry, you must be 18 or older to sign up.');
}
// Output: Sorry, you must be 18 or older to sign up.

How it works:

  • After if, the condition goes inside round brackets ( ).
  • The code to run when the condition is true goes inside curly braces { }. This group of code is called a block.
  • else is optional. Its block runs only when the condition is false.

Change age to 21 and run it again. Now you will see the welcome message. Exactly one of the two blocks always runs, never both.

Common mistake: Using a single = inside a condition. if (age = 18) does not compare; it assigns 18 to age. To compare, use ===.

else if: checking several conditions (grade calculator)

When there are more than two possibilities, add else if. JavaScript checks each condition from top to bottom and runs the first block whose condition is true. Then it skips the rest.

const score = 83;
let grade;

if (score >= 90) {
  grade = 'A';
} else if (score >= 80) {
  grade = 'B';
} else if (score >= 70) {
  grade = 'C';
} else if (score >= 60) {
  grade = 'D';
} else {
  grade = 'F';
}

console.log(`Your score is ${score}, so your grade is ${grade}.`);
// Output: Your score is 83, so your grade is B.

A score of 83 is not 90 or more, so the first block is skipped. It is 80 or more, so grade becomes 'B', and all the other checks are skipped. Notice that we didn't need to write score >= 80 && score < 90. The order of the checks does that work for us. If you put score >= 60 first, every passing student would get a D, so order matters.

Also notice let grade; is declared before the if statement. A variable declared inside a block { } with let or const only exists inside that block.

Greeting by time of day with new Date().getHours()

Let's make a page greet the visitor based on the time. new Date() creates a date object for the current moment, and .getHours() gives the current hour from 0 (midnight) to 23 (11 pm), using the visitor's own clock.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Greeting</title>
</head>
<body>
  <h1 id="greeting">Hello!</h1>

  <script>
    const hour = new Date().getHours();
    let message;

    if (hour < 12) {
      message = 'Good morning!';
    } else if (hour < 18) {
      message = 'Good afternoon!';
    } else {
      message = 'Good evening!';
    }

    document.querySelector('#greeting').textContent = message;
    console.log(`It is ${hour}:00, so the message is "${message}"`);
  </script>
</body>
</html>

Open the page and the heading changes to the right greeting. At 9 am you see "Good morning!", at 3 pm "Good afternoon!" and at 8 pm "Good evening!". To test the other messages without waiting, temporarily replace the first line with const hour = 20;.

Nested if statements and block braces

You can put an if statement inside another one. This is called nesting. It's useful when a second question only matters after the first one is answered.

const isLoggedIn = true;
const cartTotal = 45;

if (isLoggedIn) {
  if (cartTotal >= 50) {
    console.log('You get free shipping!');
  } else {
    console.log(`Add $${50 - cartTotal} more for free shipping.`);
  }
} else {
  console.log('Please log in to check out.');
}
// Output: Add $5 more for free shipping.

Notice if (isLoggedIn) without === true. Because isLoggedIn is already a boolean (and truthy values work too), you can use it directly.

Two good habits:

  • Always use curly braces, even for one line. JavaScript lets you skip them for a single statement, but adding a second line later then causes bugs that are hard to spot.
  • Indent the code inside each block (usually 2 spaces) so you can see which code belongs where.

Tip: Try not to nest more than two or three levels deep. Deep nesting is hard to read. In the next lesson you'll learn logical operators, which let you combine conditions into one.

Practice exercise

Write a "movie ticket price" program. Create a variable age. Children under 12 pay $6, people from 12 to 64 pay $12, and people 65 and over pay $8. Log a message like Your ticket costs $12. Test it with the ages 8, 30 and 70.

Hint: use if, two else if checks... or just one else if and an else. Start with the smallest age group: if (age < 12).

Key takeaways

  • An if statement runs a block of code only when its condition is true.
  • else runs when the condition is false; else if adds more conditions, checked from top to bottom.
  • Only the first matching block runs, so the order of your checks matters.
  • Use ===, !==, >, <, >= and <= to build conditions, and never a single =.
  • Always use curly braces and indent your code.