Conditionals: if, else, switch
Conditionals let your code make decisions and run different code depending on a condition. if (age >= 18) { ... } runs the code inside the block only if the condition is true. else { ... } runs instead, only if the condition was false. else if lets you chain multiple conditions in order: if (score >= 90) { ... } else if (score >= 70) { ... } else { ... } JavaScript checks each condition top to bottom and runs the first one that matches. switch is an alternative when you're checking one value against many specific possibilities: switch (day) { case "Mon": ...; break; case "Tue": ...; break; default: ...; }. Each case checks for an exact match, break stops it from "falling through" into the next case, and default runs if nothing else matched. Any value can be used in a condition, not just true/false directly JavaScript treats certain values as "falsy" (0, "", null, undefined, NaN) and everything else as "truthy," a concept worth remembering as your conditions get more complex.
Why this matters
- ·if/else lets a program react differently depending on real, changing data.
- ·else if chains let you check several ordered conditions cleanly.
- ·switch reads more clearly than a long if/else if chain when checking one value against many exact options.
Common mistakes
- ·Forgetting break in a switch case lets execution 'fall through' into the next case unintentionally.
- ·Using = (assignment) instead of == or === inside a condition is a classic, hard-to-spot bug.
- ·Misordering else if conditions (broad ones before narrow ones) can make later conditions unreachable.
Frequently asked questions
Nothing inside that block runs, and the code simply continues to whatever comes after it.
Practice questions
Question 1
Write an if/else that checks if a number variable is even or odd, and displays the result.
Question 2
Write a switch statement that displays a different message for "Mon", "Tue", and a default case.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 3
