freecoding.school100% FREE · NO SIGNUP
Script SpringsISSUE #23 of 29

if · else · else if

SparkyVSNaN the Trickster
Sparky saysif / else if / else branch your code based on conditions.

The core decision structure: if (cond) { … } else if (cond2) { … } else { … }. Conditions are coerced to boolean. Keep branches shallow — deeply nested ifs are a smell; prefer early returns (guard clauses) to flatten logic and make the happy path obvious.

Power-ups you unlock

NaN the Trickster attacks — common mistakes

Boss battleRewrite a nested if as guard clauses that return early.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>function grade(n){ if(n>=90) return 'A'; if(n>=80) return 'B'; return 'C'; }
document.getElementById('o').textContent=[95,85,70].map(grade).join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ Destructuring · Arrays · ObjectsSwitch · Case · Break · Default ›