JavaScript · Unit 2: Decisions, functions and loops · Lesson 1 of 6
if and else
if runs code only when its condition is true.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
if runs code only when its condition is true. else runs when it is false.
Chain more choices with else if. JavaScript checks them from the top and runs only the first one that is true.
The code for each branch goes in curly braces { }. Indent it so you can see which code belongs to which branch.
Worked example
JavaScript
const temp = 31;
if (temp > 30) {
console.log("Hot: drink water");
} else if (temp > 15) {
console.log("Nice day");
} else {
console.log("Bring a jacket");
}
It prints
Hot: drink water
Key terms
- if / else
- Runs code only when a condition is true; else if and else handle the other cases.
Practise it in Code Academy
It has 4 exercises (predict the output, fill in the blank, fix the broken code and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.