EasyCode365EasyCode365

If Statements

Programs need to make decisions and carry out actions based on different situations. For example, a weather app might show a sunrise graphic if it is morning, or a moon if it is nighttime.

In JavaScript, we control these choices with conditional statements.

What an if statement does

An if statement checks a condition.

If the condition is true, JavaScript runs the code inside the curly braces {}. If the condition is false, JavaScript skips that code and moves on.

First code example

Let's use the >= operator to check a user's age.

Can edit
const age = 18;

if (age >= 18) {
  console.log("You are old enough to vote.");
}

Code walkthrough

  • The keyword if tells JavaScript to start a condition.
  • The condition goes inside parentheses ().
  • age >= 18 asks: “Is age greater than or equal to 18?”
  • Because age is 18, the condition is true.
  • The message appears in the Output section after you click Run.

Using else

What if the condition is false? We can add else to give the program another block of code to run.

Can edit
const score = 45;

if (score >= 60) {
  console.log("You passed!");
} else {
  console.log("You did not pass.");
}

Here, score >= 60 is false, so JavaScript skips the if block and runs the else block instead.

If-Else Statement

Using else if

Sometimes you need to check more than two possibilities. You can use else if to test another condition before an optional else block.

We use === to check whether two values are exactly the same.

Can edit
const weather = "raining";

if (weather === "sunny") {
  console.log("Wear sunglasses.");
} else if (weather === "raining") {
  console.log("Take an umbrella.");
} else {
  console.log("Have a nice day!");
}

JavaScript checks the conditions from top to bottom. It skips "sunny", finds that "raining" is true, and sends "Take an umbrella." to the Output section.

Mini task

Edit the weather code above.

Change the weather value from "raining" to "snowing". Then click Run and check the Output section.

What message do you see?

Short quiz

Question: What happens if the condition in an if statement is false, and there is no else block?

  • A) The program crashes.
  • B) The code inside the if block runs anyway.
  • C) The code inside the if block is skipped and the program moves on.

Answer: C. If the condition is false, JavaScript skips the code inside the if block.

Small challenge

Write a program that checks a user's login status.

  • Create a variable called loginStatus.
  • Check if loginStatus is exactly equal to "yes".
  • If it is, show "Welcome back!".
  • Otherwise, show "Please log in.".
Can edit
// put your code below

console.log()

Summary

You now know how to make simple decisions in JavaScript.

  • if runs code when a condition is true.
  • else runs code when the if condition is false.
  • else if lets you check more than one condition.