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.
const age = 18;
if (age >= 18) {
console.log("You are old enough to vote.");
}Code walkthrough
- The keyword
iftells JavaScript to start a condition. - The condition goes inside parentheses
(). age >= 18asks: “Is age greater than or equal to 18?”- Because
ageis18, 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.
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.
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.
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
ifblock runs anyway. - C) The code inside the
ifblock 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
loginStatusis exactly equal to"yes". - If it is, show
"Welcome back!". - Otherwise, show
"Please log in.".
// put your code below
console.log()Summary
You now know how to make simple decisions in JavaScript.
ifruns code when a condition is true.elseruns code when theifcondition is false.else iflets you check more than one condition.