if Statements
Making decisions.
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.

- 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.
const temperature = 34;
if (temperature > 30) {
console.log("It's hot! Drink some water.");
}
console.log("Have a nice day.");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.
| key | value |
|---|---|
| if (condition) | the question |
| { ... } | code to run |
| true | runs |
| false | skipped |
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.
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?`);
}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