If/Else Chains
Learn to control program flow with if, else if, and else statements: the building blocks of decision-making in JavaScript.
What Is Conditional Logic?
Programs often need to make decisions. Should we show a welcome message or an error? Should the character jump or duck? Conditional logic lets your code choose different paths based on whether something is true or false.
The Basic if Statement
An if statement checks a condition. If it is true, the code inside the curly braces runs. If it is false, the code is skipped entirely.
Adding else: Two Paths
What if you want something to happen when the condition is false? The else block catches everything that the if does not.
The else if Chain
When you have more than two possible outcomes, chain multiple conditions together with else if. JavaScript checks each condition top to bottom and runs the first one that is true.
Anatomy of an Else-If Chain
Chained vs. Separate if Statements
Writing Conditions
A condition is any expression that evaluates to true or false. JavaScript provides comparison and logical operators to build them.
| Operator | Meaning | Example |
|---|---|---|
=== | Strict equality | x === 5 |
!== | Not equal | x !== 0 |
| \(>\) , \(<\) | Greater / less than | age > 18 |
| \(\geq\) , \(\leq\) | Greater/less or equal | score >= 90 |
&& | Logical AND | x > 0 && x < 10 |
|| | Logical OR | day === "Sat" || day === "Sun" |
How to Build an Else-If Chain
Example 1: Weather Advice
Given a temperature in Fahrenheit, print clothing advice.
Example 2: Ticket Pricing
A movie theater charges different prices by age.
Example 3: Compound Conditions
You can combine conditions using && (AND) and || (OR) inside any branch.
Nesting vs. Chaining
Common Mistakes
if (x = 5) assigns 5 to x (always truthy). Use === for comparison.Quick Reference Table
| Keyword | When to Use | How Many Per Chain? |
|---|---|---|
if |
First condition check | Exactly 1 |
else if |
Additional conditions after the first | 0 or more |
else |
Catch-all default when nothing above matched | 0 or 1 |
Question 1 of 5
Code:
let x = 15;
if (x > 20) {
console.log("A");
} else if (x > 10) {
console.log("B");
} else if (x > 5) {
console.log("C");
} else {
console.log("D");
}
What does this code print?
Question 2 of 5
What is the purpose of the else block at the end of an if/else-if chain?
Question 3 of 5
Code:
let n = 8;
if (n > 5) {
console.log("X");
}
if (n > 3) {
console.log("Y");
}
What does this code output?
Question 4 of 5
A student writes if (score = 100) instead of if (score === 100). What happens?
score to 100 (a truthy value), so the block always runs regardless of the original score.Question 5 of 5
Code:
let grade = 95;
let result;
if (grade >= 70) {
result = "Pass";
} else if (grade >= 90) {
result = "Honor Roll";
} else {
result = "Fail";
}
A student with grade 95 expects "Honor Roll" but gets "Pass". Why?