After this lesson you can make a program take different paths: show a message only for logged-in users, give a grade for a score, or refuse input that does not make sense. This is the first lesson on control flow, which means deciding what code runs and when. It builds on the comparison operators from Operators and the equality rules in Type conversion and equality.
The if statement
An if statement has a condition in parentheses and a block of code in curly braces. If the condition is true, the block runs. If it is false, JavaScript skips it.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const temperature = 31;
if (temperature > 30) {
log("It is hot. Drink some water.");
}
log("This line always runs.");
</script>The condition is any expression that produces a value. Comparisons such as >, <, >=, <=, === and !== produce true or false, which is what you usually want. Change temperature to 20 in the editor and run it again: the first message disappears, but the last line stays because it sits outside the block.
else
Add else when you want something to happen in the other case. Exactly one of the two blocks will run.
if (isLoggedIn === true) {
showDashboard();
} else {
showLoginForm();
}Because isLoggedIn is already a boolean here, you can shorten the test to if (isLoggedIn). The next lesson, Truthy and falsy values, explains exactly what the parentheses accept.
else if: more than two paths
When there are several possibilities, chain tests with else if. JavaScript checks them from top to bottom. The first condition that is true wins, its block runs, and the rest are skipped. A final else is optional and catches everything left over.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 75) {
return "B";
} else if (score >= 50) {
return "C";
} else {
return "Needs more practice";
}
}
log(grade(95));
log(grade(80));
log(grade(50));
log(grade(20));
</script>This prints A, B, C and Needs more practice, one per line. Notice that the second test is just score >= 75. It does not need to say "and less than 90", because a score of 90 or more was already handled by the first branch. That is the key idea of a chain: each branch can rely on the ones above it having failed.
It also means order matters. If you wrote the score >= 50 test first, a score of 95 would get a C, because 95 is at least 50 and the chain would stop there. Always put the most specific or strictest condition first.
Combining conditions
Often one comparison is not enough. Three operators join conditions together:
| Operator | Meaning | True when |
|---|---|---|
&& |
and | both sides are true |
|| |
or | at least one side is true |
! |
not | the value is false (it flips the result) |
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
function canRent(age, hasLicence) {
if (age >= 18 && hasLicence) {
return "You can rent a car.";
}
if (age < 18 || !hasLicence) {
return "Sorry, not today.";
}
}
log(canRent(25, true));
log(canRent(25, false));
log(canRent(16, true));
</script>The output is You can rent a car. followed by Sorry, not today. twice. Use parentheses when you mix && and ||, because && is evaluated before ||, and a reader should not need to remember that: (a || b) && c says exactly what you mean.
Early returns keep code flat
Inside a function, you can often avoid else entirely. Handle the unusual case first and return, then write the main logic without extra nesting. Compare these two shapes:
// Deeply nested
function discount(price, isMember) {
if (price > 0) {
if (isMember) {
return price * 0.9;
} else {
return price;
}
} else {
return 0;
}
}
// Flat, with early returns
function discount(price, isMember) {
if (price <= 0) return 0;
if (!isMember) return price;
return price * 0.9;
}Both do the same thing, but the second reads like a list of rules. Functions are covered properly in the next section; for now, just notice how little nesting is needed.
A note on braces
JavaScript allows if (x) doSomething(); without braces, but only the one next statement belongs to the if. People regularly add a second line later, indent it, and assume it is inside the condition when it is not. Using braces every time costs a few characters and avoids that whole class of bug.
Common mistakes
- Using
=instead of===.if (score = 10)assigns 10 toscoreand the condition is then always true. Read your comparisons aloud: "if score equals ten" needs three equals signs. - Writing a range the way you say it.
if (0 < x < 10)does not mean "x is between 0 and 10". JavaScript evaluates0 < xfirst, getstrueorfalse, then compares that to 10. Writex > 0 && x < 10. - Putting a general test before a specific one. In an
else ifchain the first match wins. Putscore >= 50beforescore >= 90and nobody will ever get an A. - A semicolon straight after the condition.
if (ready);ends the statement immediately, so the block below it is not controlled by theifat all and always runs. - Comparing numbers that came from a form as if they were numbers. Input values are strings.
"10" > "9"isfalsebecause strings compare character by character. Convert withNumber()first, as covered in the type conversion lesson. - Repeating the same condition in several places. If you test
user.age >= 18in five spots, store it once in a well-named constant such asisAdult.
Exercise
Write a function describeTemperature(celsius) that returns:
"freezing"when the temperature is 0 or below,"cold"when it is above 0 but below 15,"pleasant"from 15 up to and including 25,"hot"above 25.
Test it with -5, 0, 10, 15, 25 and 30, and log each result. Then add a check at the top: if celsius is not a number (hint: typeof celsius !== "number"), return "not a temperature". Finally, ask yourself whether your branches would still work if you shuffled their order. If not, you have found the places where order matters.
Next up: Truthy and falsy values, which explains why if (name) works even though name is not a boolean.
Key points
- An if statement runs its block only when the condition in parentheses is true.
- else catches everything the earlier conditions did not, and else if adds more tests in between.
- JavaScript checks the conditions from top to bottom and runs only the first block that matches.
- Use === for comparisons, and combine tests with && (and), || (or) and ! (not).
- Order matters: put the most specific condition first.