Lesson 4: Conditional Statements - Making Decisions
What You'll Learn
- How to use
ifstatements to make decisions - How to add alternative paths with
else - How to check multiple conditions with
else if - How to use the ternary operator as a shortcut
- How to nest conditions
Why This Matters
Programs need to make decisions based on conditions. Should we show an error message? Is the user old enough? Is it time to level up? Conditional statements let your code choose different paths based on the situation.
---
Part 1: The if Statement
The if statement runs code only when a condition is true.
lesson-04/conditionals.js
Basic if Statement
const age = 20;
if (age >= 18) {
console.log("You are an adult!");
}
console.log("Program continues...");
Output:
You are an adult!
Program continues...
Understanding the Syntax
if (condition) {
// Code here runs ONLY if condition is true
}
if: The keyword that starts the statement(condition): An expression that evaluates totrueorfalse{ }: Curly braces contain the code to run if true- Indentation: Code inside braces is indented (2 or 4 spaces) for readability
What Happens?
- The program checks if
age >= 18is true - If true: runs the code inside
{ } - If false: skips the code inside
{ } - Either way: continues with the rest of the program
---
Part 2: The else Statement
The else statement provides an alternative when the condition is false.
const temperature = 15;
if (temperature > 20) {
console.log("It's warm outside!");
} else {
console.log("It's cold outside!");
}
If temperature is 25:
if (condition) {
// Runs if condition is TRUE
} else {
// Runs if condition is FALSE
}
Think of it like a fork in the road - the program must take one path or the other, never both.
---
Part 3: The else if Statement
When you have more than two possibilities, use else if:
const grade = 85;
if (grade >= 90) {
console.log("Grade: A");
} else if (grade >= 80) {
console.log("Grade: B");
} else if (grade >= 70) {
console.log("Grade: C");
} else if (grade >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
Output (for grade = 85):
// ❌ WRONG ORDER
if (grade >= 60) { // This catches everything >= 60
console.log("Grade: D");
} else if (grade >= 90) { // Never reached!
console.log("Grade: A");
}
// ✅ CORRECT ORDER
if (grade >= 90) { // Check highest first
console.log("Grade: A");
} else if (grade >= 60) { // Check lower values after
console.log("Grade: D");
}
---
Part 4: Combining Conditions
You can use logical operators (&&, ||, !) in conditions:
Using AND (&&)
const age = 25;
const hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive!");
} else {
console.log("You cannot drive.");
}
Both conditions must be true for the code to run.
Using OR (||)
const day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
} else {
console.log("It's a weekday.");
}
At least one condition must be true for the code to run.
Using NOT (!)
const isRaining = false;
if (!isRaining) {
console.log("Let's go outside!");
} else {
console.log("Stay inside.");
}
The ! flips the boolean value: !false becomes true.
Complex Conditions
const age = 22;
const isStudent = true;
const hasID = true;
if ((age >= 18 && age < 65) && (isStudent || hasID)) {
console.log("You get a discount!");
} else {
console.log("Regular price.");
}
Use parentheses to group conditions and make your logic clear.
---
Part 5: Nested if Statements
You can put if statements inside other if statements:
const age = 25;
const hasTicket = true;
if (age >= 18) {
console.log("You are old enough.");
if (hasTicket) {
console.log("You can enter!");
} else {
console.log("You need a ticket.");
}
} else {
console.log("You are too young.");
}
How Nesting Works
- First, check if
age >= 18 - If true, check if
hasTicket - Each level of nesting adds another decision point
- When you need to check a second condition only if the first is true
- When decisions depend on previous decisions
- Too many levels (3+) make code hard to read
- Use
&&instead when possible
// Instead of this (nested):
if (age >= 18) {
if (hasTicket) {
console.log("You can enter!");
}
}
// Write this (combined):
if (age >= 18 && hasTicket) {
console.log("You can enter!");
}
---
Part 6: The Ternary Operator (Shortcut)
For simple if/else, you can use the ternary operator:
const age = 20;
// Using if/else (long way)
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
// Using ternary operator (short way)
const status2 = age >= 18 ? "adult" : "minor";
console.log(status2); // Output: adult
Ternary Syntax
const temperature = 25;
const weather = temperature > 20 ? "warm" : "cold";
console.log(weather); // warm
const score = 95;
const passed = score >= 60 ? true : false;
console.log(passed); // true
// Can even use in console.log directly
const points = 150;
console.log(points > 100 ? "High score!" : "Keep trying!");
When to Use Ternary
✅ Good use cases:- Simple true/false assignments
- Short, readable expressions
- Returning values
- Complex logic
- Multiple statements
- When if/else is clearer
---
Part 7: Switch Statements
For checking one variable against many values, use switch:
const dayNumber = 3;
switch (dayNumber) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
case 7:
console.log("Weekend!");
break;
default:
console.log("Invalid day");
}
Output:
switch (variable) {
case value1:
// Code if variable === value1
break;
case value2:
// Code if variable === value2
break;
default:
// Code if no cases match
}
Important: The break Statement
// ❌ WITHOUT break (falls through)
const x = 1;
switch (x) {
case 1:
console.log("One");
// NO BREAK - continues to next case!
case 2:
console.log("Two");
}
// Output: One
// Two
// ✅ WITH break (stops at match)
switch (x) {
case 1:
console.log("One");
break; // Stops here
case 2:
console.log("Two");
break;
}
// Output: One
When to Use Switch vs if/else
Use switch when:- Checking one variable against many specific values
- Values are discrete (1, 2, 3 or "red", "blue", "green")
- Checking ranges (age > 18)
- Complex conditions (age > 18 && hasLicense)
- Different variables in each condition
---
Practice Exercises
Exercise 1: Age Categories
Write a program that categorizes age:
- 0-12: "Child"
- 13-19: "Teenager"
- 20-59: "Adult"
- 60+: "Senior"
Exercise 2: Login System
Check if username is "admin" AND password is "1234". Print "Access granted" or "Access denied".
Exercise 3: Grade Calculator
Take a score (0-100) and print the letter grade (A, B, C, D, F).
Exercise 4: BMI Calculator
Calculate BMI:weight / (height * height)
- BMI < 18.5: "Underweight"
- BMI 18.5-24.9: "Normal"
- BMI 25-29.9: "Overweight"
- BMI >= 30: "Obese"
Exercise 5: Ticket Pricing
Calculate ticket price:
- Age < 5: Free
- Age 5-17: $10
- Age 18-64: $20
- Age 65+: $15
- Add $5 if it's a weekend
Exercise 6: Month Name
Use a switch statement to convert month number (1-12) to name.
---
Common Mistakes
Mistake 1: Missing Curly Braces (Single Statement)
// Works but risky:
if (age >= 18)
console.log("Adult");
// Better - always use braces:
if (age >= 18) {
console.log("Adult");
}
Mistake 2: Assignment Instead of Comparison
const x = 5;
if (x = 10) { // ❌ WRONG! Assigns 10 to x
console.log("Equal");
}
if (x === 10) { // ✅ CORRECT! Compares
console.log("Equal");
}
Mistake 3: Unreachable Code
if (age >= 18) {
console.log("Adult");
} else if (age >= 21) { // ❌ Never reached!
console.log("Can drink");
}
// Fix: Check specific case first or use nested if
Mistake 4: Missing break in Switch
switch (day) {
case 1:
console.log("Monday");
// ❌ Forgot break! Falls through to Tuesday
case 2:
console.log("Tuesday");
break;
}
---
Key Concepts Summary
| Statement | Use Case | Example |
|---|---|---|
| if | Single condition | if (x > 10) { } |
| if/else | Two paths | if (x > 10) { } else { } |
| else if | Multiple conditions | if (...) { } else if (...) { } |
| Ternary | Simple true/false | x > 10 ? "yes" : "no" |
| switch | Multiple specific values | switch (day) { case 1: ... } |
What You Learned
- ✅ How to use if statements to make decisions
- ✅ How to provide alternative paths with else
- ✅ How to check multiple conditions with else if
- ✅ How to combine conditions with &&, ||, and !
- ✅ How to use nested if statements
- ✅ How to use the ternary operator for simple conditions
- ✅ How to use switch statements for multiple values
- ✅ The importance of break in switch statements
What's Next?
In the next lesson, you'll learn about functions - how to organize your code into reusable blocks that can be called whenever needed!