AI Hints
JavaScript · Lesson 19 of 138

if Statements

Making decisions.

⏱ 2 min read▶ Video at 22:23🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Programs need to make decisions. If the password is right, let the user in. If the cart is empty, show a message. An if statement runs some code only when a condition is true.

if Statements
From the video: if Statements
  • Programs make decisions
  • Right password? Empty cart?
  • if runs code when true

Your first if

After if, the condition goes in round brackets. The code to run goes in curly braces. If the condition is true, the code runs. If it's false, JavaScript skips it. Run it. The temperature is over thirty, so we see the warning. The last line always runs.

app.jsjavascript
const temperature = 34;

if (temperature > 30) {
  console.log("It's hot! Drink some water.");
}

console.log("Have a nice day.");
Output
It's hot! Drink some water.
Have a nice day.

Reading it out loud

Read the code like a sentence. If temperature is greater than thirty, print the warning. The lines inside the braces are indented, so it's easy to see what belongs to the if. Your editor will usually indent for you.

keyvalue
if (condition)the question
{ ... }code to run
trueruns
falseskipped

Conditions with variables

The condition can be any expression that gives true or false. Here we store the result of a comparison in a variable with a clear name, then use it in the if. That often makes the code read more like a sentence. Only the second message prints, because the cart isn't empty. Run it.

app.jsjavascript
const cartItems = 3;
const isEmpty = cartItems === 0;

if (isEmpty) {
  console.log("Your cart is empty.");
}
if (!isEmpty) {
  console.log(`You have ${cartItems} items. Ready to check out?`);
}
Output
You have 3 items. Ready to check out?

Summary

An if statement runs its code only when the condition is true. Next, else, for what to do otherwise.

Key takeaways
  • if (condition) { }
  • Runs when true
  • Indent the inside
Next up: else if and else — more choices