JavaScript if, else if and else Statements
Quick answer
An if statement conditionally executes a statement or block. An else branch handles the opposite outcome; an else-if chain selects the first matching condition.
How it works
Write if (condition) { ... } else { ... }. The condition is tested for truthiness. In an else-if chain, later conditions are skipped once a branch is selected. Use braces even for single statements to avoid confusing nested else associations. Separate if statements are independent.
const temperature = 12;if (temperature < 15) { console.log("coat"); } else { console.log("light jacket"); }Expected output in Node.js:
coatOnly the true branch runs.
const score = 90;if (score >= 90) { console.log("excellent"); } else if (score >= 60) { console.log("pass"); } else { console.log("retry"); }Expected output in Node.js:
excellentAlthough both thresholds hold, the first branch wins.
Common mistakes
Put more specific thresholds before broader overlapping conditions. Do not put a stray semicolon immediately after if (condition).
Practice
Classify a temperature as cold, mild or hot using non-overlapping ranges.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript if, else if and else Statements — Knowledge Check
Apply the taught concept and reason about the result.
For score 95, which branch runs in if(score>=90){A()} else if(score>=60){B()} ?
What does an else branch handle?
How are two separate if statements evaluated?
What is the effect of if(false){ console.log("yes"); } ?
Which order is correct for overlapping score thresholds?