Every day, you make hundreds of tiny decisions without even thinking about them.
If it's raining, take an umbrella. If you're hungry, eat something. If the phone battery is low, plug it in. If someone says "the last slice of pizza is for whoever wants it," move fast.
Programs need to make decisions too. If the password is correct, log the user in. If the player's health reaches zero, show "Game Over." If the cart is empty, disable the checkout button.
In JavaScript, decisions are made with the if statement:
const isRaining = true;
if (isRaining) {
console.log("Take an umbrella! ☂️");
}
console.log("Have a nice day!");
It prints
Take an umbrella! ☂️ Have a nice day!
Here's how it works:
- The keyword
ifstarts the decision. - Inside the parentheses
( )goes the condition: a question that's either true or false. - Inside the curly braces
{ }goes the code to run only if the condition is true. This is called the block.
If the condition is false, JavaScript skips the entire block and carries on with whatever comes after it:
const isRaining = false;
if (isRaining) {
console.log("Take an umbrella! ☂️");
}
console.log("Have a nice day!");
It prints
Have a nice day!
The umbrella message was skipped completely. But "Have a nice day!" is outside the if block, so it always runs.
Using comparisons as conditions
Most of the time, the condition will be a comparison from Grade 3:
const temperature = 34;
if (temperature > 30) {
console.log("It's hot! Drink some water. 🥤");
}
const score = 100;
if (score === 100) {
console.log("PERFECT SCORE! 🏆");
}
It prints
It's hot! Drink some water. 🥤 PERFECT SCORE! 🏆
Notice how the code inside the curly braces is pushed in by two spaces? That's called indentation. JavaScript doesn't need it, but humans do. It makes it instantly obvious which code belongs inside the if. VS Code will usually indent for you automatically. You can also tidy up a whole file with Format Document (right-click in the editor to find it).