All tutorials
Basics

Conditions: if / else / switch

Control which code runs based on a condition.

1. Explanation

if / else if / else lets you branch. switch is convenient when comparing one value to many constants. Every condition is coerced to boolean — falsy values are: false, 0, '', null, undefined, NaN. Everything else is truthy.

2. Syntax

js
if (condition) { ... } else if (...) { ... } else { ... }

switch (value) { case 'a': ...; break; default: ... }

3. Example

Try it yourself
Console
Click Run to see output.

4. Expected output

output
You can vote
Start of week

5. Common mistakes

  • Forgetting 'break' in a switch — execution falls through to the next case
  • Using = instead of === inside an if (assignment instead of comparison)
  • Relying on truthy/falsy without realising 0 and '' are falsy

6. Practice questions

  1. Write a program that classifies a temperature as cold / warm / hot
  2. Build a grade calculator: 90+ A, 80+ B, 70+ C, else F
  3. Use switch to convert a number 1-7 to a day name
→ Try more practice problems