JavaScript Tutorial
JavaScript If Else
if runs a block when a test is true. else if and else cover the other cases.
if runs a block
Write if, a test in parentheses, then a brace-wrapped block. If the test is true, the block runs. If it is false, JavaScript skips the block and continues after it.
Always use braces, even for one statement. A later edit that adds a second line without braces will not do what it looks like. This tutorial never omits them.
Example
const score = 72;
let message = "too low";
if (score >= 50) {
message = "pass";
}
console.log(message);
document.body.textContent = message;
Change score in /javascript/try. At 49 the message staystoo low unless you add else.
else covers the rest
else runs when the if test is false. Exactly one of the two blocks runs. You do not need a second test for the leftover case.
Example
const score = 41;
let message;
if (score >= 50) {
message = "pass";
} else {
message = "retry";
}
console.log(message);
document.body.textContent = message;
else if chains more tests
Each else if is another test, tried only when every test above it failed. Order matters: the first true test wins and the rest are skipped. Put the narrow cases first when ranges overlap.
Example
const score = 83;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "D";
}
console.log(grade);
document.body.textContent = grade;
At 83 the first test is false, the second is true, and grade becomes "B". The>= 70 test never runs.
Tests you will write
| Test | True when |
|---|---|
score >= 50 | The number is at least 50 |
name === "Ada" | The string is exactly Ada |
list.length === 0 | The array has no items |
Number.isFinite(n) | n is an ordinary number |
Combine tests with && (both must be true) and || (either may be true). Wrap each comparison in parentheses if the line is getting hard to read.
Truthy tests and nesting
if (name) is true for any non-empty string. That is handy for “did the user type something?” It is the wrong test for “is this the string false?” — that string is truthy.
You can put an if inside another block. Keep it shallow. A chain of else if is usually easier to follow than three levels of nesting.
Example
const name = "Ada";
const score = 91;
let result = "skip";
if (name) {
if (score >= 90) {
result = name + " distinguished";
} else {
result = name + " recorded";
}
}
console.log(result);
document.body.textContent = result;
What to remember
- The test goes in parentheses. The body goes in braces.
elseis the leftover.else ifadds another test in order.- The first true branch wins. Later branches do not run.
- Use
===in tests so strings and numbers stay distinct.
Next: switch — pick a case that strictly matches, then break so you do not fall through.