Learn JavaScript
❯ control_flow.if_else

if, else if, else Statements in JavaScript

$concept

An if statement runs its block when the condition is truthy; else if chains test alternatives in order and a trailing else catches everything left over. Conditions accept any value through truthiness β€” comparisons most often, but also direct values, lengths, and existence checks.

Braces are optional for single statements but omitting them invites dangling-else confusion when lines are added later. Early returns (guard clauses) flatten nested validation into a readable sequence of rejections before the real work.

$how it works
1

Truthy runs the block

if (score >= 60) executes only when the comparison is truthy; any truthy value (nonzero, non-empty) qualifies.

2

else if chains alternatives

Each tests only when everything above failed β€” first-match-wins ordering for grades and ranges.

3

else catches the rest

A final else needs no condition and guarantees some path executes.

4

Guard early, brace always

if (!input) return; up front beats nesting; braces on every branch prevent future dangling-else bugs.

$example
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C or below");
}
Output
B
1score >= 90 is false for 85 β€” first block skipped.
2score >= 80 is true β€” B prints and the chain exits.
3Exactly one branch ever executes.
$use cases
Grading and range classification with ordered chains
Guard clauses rejecting bad input before main logic
Truthy existence checks (if (user)) for optional values
Trailing else fallbacks in parsers and menus

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.