JavaScript Conditions
A condition is a check that decides whether a block of code runs. The if statement runs its block only when the check is true.
Run a block
The age test is true here. The line inside the braces runs.
const age = 18;
if (age >= 18) {
console.log("Adult");
}The other branch
The age test is false here. The else block runs instead.
const age = 12;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Young");
}A chain of checks
The score fails the first check and passes the second. The middle block runs.
const score = 75;
if (score >= 90) {
console.log("Top marks");
} else if (score >= 50) {
console.log("Pass");
} else {
console.log("Try again");
}Example
const marks = 42;
if (marks >= 80) {
console.log("Great result");
} else if (marks >= 50) {
console.log("Fair result");
} else {
console.log("More practice needed");
}Key points
- The condition sits in parentheses after the word if.
- The block sits in braces and holds the statements that may run.
- else adds a block that runs when the condition is false.
- else if adds another check when the first condition is false.
- Checks in a chain run in order, and the first true check wins.
- An if statement can sit inside another if block, which is called nesting.
In this example, the marks value fails the first check and the second check. The final else block runs because no check was true. Only one line is logged.
Note
the ternary operator is the one-line cousin of if and else, taught with comparisons.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
When does the else block of an if statement run?