Control Flow and Conditionals

Learn how to make decisions in your code with conditional statements and control program execution flow.

What is Control Flow?

// Control flow determines execution order
let hour = 14; // 2 PM
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}
Good afternoon!

Control flow allows your program to make decisions and execute different code blocks based on conditions.

If/Else Statements

let temperature = 28;
if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("Nice weather!");
} else if (temperature > 10) {
console.log("A bit chilly");
} else {
console.log("Too cold!");
}
Nice weather!

Use if, else if, and else to handle multiple conditions.

Combining Conditions

let age = 25;
let hasLicense = true;

// AND operator (both must be true)
if (age >= 18 && hasLicense) {
console.log("You can drive!");
}

// OR operator (at least one true)
if (age < 3 || age > 70) {
console.log("Special ticket price applies");
}

// NOT operator
if (!hasLicense) {
console.log("Cannot drive");
}
You can drive!

Combine conditions using logical operators: && (AND), || (OR), ! (NOT).

Ternary Operator

// Shorthand for simple if/else
let isMember = true;
let fee = isMember ? "$5.00" : "$10.00";
console.log(fee);

// Can be used for assignment or execution
let score = 85;
score > 90 ? console.log("Excellent!") : console.log("Good job!");
$5.00
Good job!

Syntax: condition ? exprIfTrue : exprIfFalse

Switch Statements

let day = "Tuesday";
let message;

switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
message = "Weekday";
break;
case "Friday":
message = "Almost weekend!";
break;
case "Saturday":
case "Sunday":
message = "Weekend!";
break;
default:
message = "Invalid day";
}
console.log(message);
Weekday

Use switch for multiple cases. Always include break to prevent fallthrough.

Truthy and Falsy Values

// Falsy values (evaluate to false):
false, 0, "", null, undefined, NaN

// Truthy values (evaluate to true):
true, 1, "hello", [], {}, 42, "0"

// Practical example:
let username = "";
if (username) {
console.log("Welcome " + username);
} else {
console.log("Please enter a username");
}
Please enter a username

JavaScript automatically converts values to booleans in conditionals. Know what evaluates to true/false.

Common Conditional Mistakes

// 1. Using assignment (=) instead of comparison (== or ===)
let loggedIn = false;
if (loggedIn = true) { /* ❌ Always true! */ }

// 2. Forgetting break in switch statements
case "Monday":
message = "Start of week";
// ❌ Missing break - will execute next case!

// 3. Confusing == and ===
if (0 == "0") { /* true */ }
if (0 === "0") { /* false */ }

// 4. Unnecessary else after return
if (x > 10) {
return true;
} else { // ❌ Unnecessary
return false;
}

Always test edge cases and use strict equality (===) to avoid subtle bugs.

Practical Example: Grading System

function assignGrade(score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 70) return "C";
else if (score >= 60) return "D";
else return "F";
}

// With switch (range example)
function getGradeComment(grade) {
switch (grade) {
case "A": return "Excellent!";
case "B": return "Good job!";
case "C": return "Average";
case "D": return "Needs improvement";
case "F": return "Failed";
default: return "Invalid grade";
}
}
assignGrade(85) → "B"
getGradeComment("B") → "Good job!"

Interactive Conditionals

// Grade button handler
document.getElementById("gradeBtn").addEventListener("click", () => {
let score = parseInt(document.getElementById("scoreInput").value);
let grade;

if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else grade = "F";

document.getElementById("output").textContent = `Grade: ${grade}`;
});

// Weekday button handler
document.getElementById("weekdayBtn").addEventListener("click", () => {
let day = document.getElementById("dayInput").value;
let type;

switch(day.toLowerCase()) {
case "saturday":
case "sunday":
type = "weekend";
break;
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
type = "weekday";
break;
default:
type = "invalid day";
}

document.getElementById("output").textContent = `Day type: ${type}`;
});

Your Task: Discount Calculator

Create JavaScript code that:

  1. Adds a click handler for the "Check Discount" button
  2. When clicked:
    • Generates a random age between 5-80 (use Math.floor(Math.random() * 76) + 5)
    • Generates a random membership status (true/false)
    • Determines discount eligibility:
      • Children (under 12): 30% discount
      • Seniors (over 65): 25% discount
      • Members: 15% discount (any age)
      • Tuesday special: Additional 10% discount (use ternary)
    • Display results in format:
      Age: 34, Member: true, Tuesday: false
      Discount: 15%
      Final price: $85.00 (from $100)
  3. Use at least:
    • One if/else if/else chain
    • One ternary operator
    • Logical operators (&& and/or ||)

Challenge: Apply maximum 40% discount and handle multiple discounts

Tip: Start with base price $100, apply discounts sequentially

Section 1/10What is Control Flow?

What is Control Flow?

Control flow allows your program to make decisions and execute different code blocks based on conditions.

Control Flow and Conditionals

Learn how to make decisions in your code with conditional statements and control program execution flow.

What is Control Flow?

// Control flow determines execution order
let hour = 14; // 2 PM
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}
Good afternoon!

Control flow allows your program to make decisions and execute different code blocks based on conditions.

Preview