The Traffic Light Analogy
You're driving and approach a traffic light. What do you do?
- If the light is green → Go
- Else if the light is yellow → Slow down
- Else (it's red) → Stop
You don't even think about it - you automatically make decisions based on what you see.
That's exactly what conditionals do in programming.
They let your code make choices. "IF this is true, do this. ELSE, do that."
Without conditionals, programs would be like robots that do the exact same thing every time, regardless of the situation. With conditionals, programs can respond intelligently to different circumstances.
Why Conditionals Matter
Think about your daily phone use:
- If you have a new message → Show notification
- If your battery is low → Show warning
- If face matches → Unlock phone
Or shopping online:
- If item is in stock → Show "Add to Cart"
- If you're a member → Apply discount
- If cart total > $50 → Free shipping
Every app, website, and program you use is constantly making these decisions. Conditionals are how.
The Basic Structure
At its simplest, a conditional asks a yes/no question:
IF (something is true)
then do this
Example:
IF (age >= 18)
print "You can vote"
That's it! Check a condition, run code if it's true.
The condition usually boils down to true or false:
age >= 18→ Is this true? → Yes (true) or No (false)temperature > 30→ Is this true? → Yes or Nousername === "admin"→ Is this true? → Yes or No
If-Else: Two Paths
What if you want to do something when the condition is FALSE?
IF (it's raining)
bring umbrella
ELSE
wear sunglasses
In a simple if/else, you typically take one branch.
Real example:
if (age >= 18) {
console.log("Welcome to the site");
} else {
console.log("Sorry, you need to be 18 or older");
}
Else-If: Multiple Paths
Sometimes you have more than two options:
IF (score >= 90) → A
ELSE IF (score >= 80) → B
ELSE IF (score >= 70) → C
ELSE IF (score >= 60) → D
ELSE → F
The program checks each condition in order. The FIRST one that's true runs, then it skips the rest.
Important: Order matters! Check from most specific to least specific.
How Conditions Work
A condition is just a question with a yes/no answer.
Comparison operators:
| Symbol | Meaning | Example |
|---|---|---|
=== | Equals (exactly same) | name === "Alice" |
!== | Not equals | status !== "closed" |
> | Greater than | score > 100 |
< | Less than | age < 18 |
>= | Greater or equal | balance >= 0 |
<= | Less or equal | items <= 10 |
Combining conditions:
| Symbol | Meaning | Example |
|---|---|---|
&& | AND (both are true) | age >= 21 && hasID |
| OR | OR (at least one true) | isStudent OR isSenior |
! | NOT (flip true/false) | !isLoggedIn |
Real-World Examples
1. Login System
IF (username exists AND password matches)
Log them in
ELSE
Show "Invalid credentials"
2. E-commerce Discounts
IF (customer is premium member)
Apply 20% discount
ELSE IF (cart total > $100)
Apply 10% discount
ELSE IF (it's Black Friday)
Apply 5% discount
ELSE
No discount
3. Weather App
IF (temperature > 30)
Show "Hot" with sun icon
ELSE IF (temperature > 20)
Show "Warm" with cloud icon
ELSE IF (temperature > 10)
Show "Cool" with jacket suggestion
ELSE
Show "Cold" with snowflake icon
4. Game Logic
IF (player health <= 0)
Game over
ELSE IF (all enemies defeated)
Level complete
ELSE
Continue playing
Switch: When You Have Many Options
If you're checking the same variable against many specific values, switch is cleaner:
switch (day) {
case "Monday":
console.log("Start of work week");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Regular day");
}
When to use switch vs if-else:
| Use Switch | Use If-Else |
|---|---|
| Checking one variable against many values | Checking different conditions |
| Exact matches | Ranges (>, <, >=) |
| Days, months, menu options | Complex logic with && and OR |
Common Mistakes
Mistake 1: Assignment Instead of Comparison
// WRONG - This assigns 5 to x!
if ((x = 5)) {
// Usually runs because assignment returns the assigned value
}
// CORRECT - This compares
if (x === 5) {
// Runs when x equals 5
}
The single = assigns. The triple === compares.
Mistake 2: Forgetting That Order Matters
// WRONG - Order can produce unexpected grades
if (score >= 70) {
grade = "C";
} else if (score >= 80) {
// Typically won't reach here
grade = "B";
} else if (score >= 90) {
// Typically won't reach here
grade = "A";
}
// CORRECT - Check highest first
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
}
Mistake 3: Over-Nesting
Too many nested conditions become hard to read:
// Hard to follow
if (a) {
if (b) {
if (c) {
doSomething();
}
}
}
// Better - use "guard clauses"
if (!a) return;
if (!b) return;
if (!c) return;
doSomething();
Truthy and Falsy (JavaScript Weirdness)
In JavaScript, conditions don't have to be exactly true or false. Some values are "truthy" (treated as true) and some are "falsy" (treated as false).
Falsy values (treated as false):
false0""(empty string)nullundefinedNaN
Everything else is truthy:
- Any non-zero number
- Any non-empty string
- Arrays (even empty ones!)
- Objects (even empty ones!)
This is useful but can be confusing:
if (userName) {
// Runs if userName exists and isn't empty
}
FAQ
Q: When should I use switch vs if-else?
Use switch when checking one variable against multiple exact values (like days of the week). Use if-else for ranges, comparisons, or complex conditions.
Q: What is short-circuit evaluation?
With &&, if the first condition is false, the second isn't even checked (it can't make the whole thing true). This lets you write defensive code:
if (user && user.name) {
// Checks user.name after verifying user exists
}
Q: Should I usually use === instead of ==?
Often, yes. The === checks type AND value (strict equality). The == can have surprising results because JavaScript tries to convert types.
Q: What's the ternary operator?
A shorthand for simple if-else:
const status = age >= 18 ? "adult" : "minor";
It means: "If age >= 18, use 'adult', else use 'minor'". It's often clearer when kept to simple expressions.
Q: Can I have if without else?
Yes. If you need to do something when a condition is true, you don't need else.
Q: How do I check multiple conditions?
Use && (AND) or || (OR):
&&is truthy when both sides are truthy||is truthy when at least one side is truthy
Summary
Conditionals let your programs make decisions. They're the foundation of all program logic.
Key Takeaways:
- Conditionals check if something is true or false, then act accordingly
- Use
iffor one condition,elsefor the alternative - Use
else iffor multiple options ===compares,=assigns (don't confuse them!)- Order your conditions from most specific to least specific
- Switch is cleaner when checking one variable against many values
- Avoid deep nesting - use guard clauses instead
Every interesting program uses conditionals. They're how code responds to the real world!
Leave a Comment
Comments (0)
Be the first to comment on this concept.
Comments are approved automatically.