Control Flow

1. Welcome and Icebreaker:

  • Welcome! Can you share a situation (in coding or real life) where you had to make a decision based on multiple conditions?

2. Outline the Session:

  • Today we’ll cover control flow statements in TypeScript: if/else, switch, for loops, while loops, and do-while loops.
  • We’ll see how to use them to direct the execution path of our programs.
  • Learning Outcomes: You’ll be able to implement conditional logic and iterative processes in TypeScript.
  • Let’s get coding!

3. Concept Explanation:

  • Control flow statements allow you to control the order in which the statements in your program are executed.

  • 1. if / else if / else Statement:

    • Executes a block of code if a specified condition is true.
    • else if allows checking multiple conditions.
    • else provides a default block of code to execute if no preceding conditions are true.
    if (condition1) {
      // block of code to be executed if condition1 is true
    } else if (condition2) {
      // block of code to be executed if condition1 is false and condition2 is true
    } else {
      // block of code to be executed if condition1 and condition2 are false
    }
    
  • 2. switch Statement:

    • Evaluates an expression and matches its value against a series of case clauses.
    • Executes statements associated with the first matching case.
    • break is crucial to prevent “fall-through” to subsequent cases.
    • default clause is optional and executes if no case matches.
    switch (expression) {
      case value1:
        // statements executed when the result of expression matches value1
        break;
      case value2:
        // statements executed when the result of expression matches value2
        break;
      // ... more cases
      default:
        // statements executed when no values match
    }
    
  • 3. for Loop:

    • Repeats a block of code a known number of times.
    • Consists of three optional expressions: initialization, condition, and final-expression (increment/decrement).
    for (initialization; condition; finalExpression) {
      // code block to be executed
    }
    
    • for...of loop: Iterates over iterable objects (like arrays, strings, maps, sets). It gives you the values of the properties.
    for (const item of iterable) {
      // code block to be executed with item
    }
    
    • for...in loop: Iterates over the enumerable properties of an object. It gives you the keys (or indices for arrays).
    for (const key in object) {
      // code block to be executed with key
      // if (object.hasOwnProperty(key)) { /* recommended check */ }
    }
    
  • 4. while Loop:

    • Repeats a block of code as long as a specified condition is true.
    • The condition is evaluated before executing the loop body.
    while (condition) {
      // code block to be executed
    }
    
  • 5. do...while Loop:

    • Similar to a while loop, but the condition is evaluated after executing the loop body.
    • This means the loop body will always execute at least once.
    do {
      // code block to be executed
    } while (condition);
    
  • break and continue Statements:

    • break: Exits the current loop (for, while, do-while) or switch statement prematurely.
    • continue: Skips the current iteration of a loop and proceeds to the next iteration.

4. Live Coding Demonstration:

console.log("--- if / else if / else ---");
let temperature: number = 25;
if (temperature < 0) {
  console.log("It's freezing!");
} else if (temperature < 20) {
  console.log("It's cool.");
} else if (temperature < 30) {
  console.log("It's warm.");
} else {
  console.log("It's hot!");
}

console.log("\n--- switch Statement ---");
let day: number = new Date().getDay(); // Sunday = 0, Monday = 1, ...
let dayName: string;
switch (day) {
  case 0:
    dayName = "Sunday";
    break;
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  default:
    dayName = "Unknown Day";
    break;
}
console.log(`Today is ${dayName}.`);

console.log("\n--- for Loop ---");
for (let i: number = 0; i < 5; i++) {
  console.log(`For loop iteration: ${i}`);
}

console.log("\n--- for...of Loop (Arrays) ---");
let colors: string[] = ["red", "green", "blue"];
for (const color of colors) {
  console.log(`Color: ${color}`);
}

console.log("\n--- for...in Loop (Objects) ---");
const person = {
  name: "Alice",
  age: 30,
  city: "New York"
};
for (const key in person) {
  if (person.hasOwnProperty(key)) { // Good practice
    console.log(`${key}: ${person[key as keyof typeof person]}`);
  }
}

console.log("\n--- while Loop ---");
let count: number = 0;
while (count < 3) {
  console.log(`While loop count: ${count}`);
  count++;
}

console.log("\n--- do...while Loop ---");
let attempts: number = 0;
do {
  console.log(`Do...while attempt: ${attempts}`);
  attempts++;
} while (attempts < 0); // Condition is false, but loop runs once

console.log("\n--- break and continue ---");
console.log("Break example:");
for (let j: number = 0; j < 10; j++) {
  if (j === 5) {
    console.log("Breaking at 5");
    break; // Exit the loop
  }
  console.log(`j = ${j}`);
}

console.log("\nContinue example:");
for (let k: number = 0; k < 5; k++) {
  if (k === 2) {
    console.log("Skipping 2");
    continue; // Skip current iteration
  }
  console.log(`k = ${k}`);
}

5. Tasks:

  • Short Exercise:
    1. if/else: Write a program that checks if a number is positive, negative, or zero and prints the result.
    2. switch: Create a variable fruit and assign it a fruit name (e.g., “apple”, “banana”, “orange”). Use a switch statement to print a message about the fruit (e.g., “Apples are red.”, “Bananas are yellow.”). Include a default case for unknown fruits.
    3. for loop: Print the numbers from 1 to 10 using a for loop.
    4. for...of loop: Create an array of your favorite hobbies. Use a for...of loop to print each hobby.
    5. while loop: Write a while loop that prints numbers from 5 down to 1.
    6. do...while loop: Simulate a dice roll. Use a do...while loop to keep rolling a 6-sided die (generate a random number from 1 to 6) until you roll a 6. Print each roll and the final message “You rolled a 6!”.
    7. break/continue: Write a for loop that iterates from 1 to 10. If the number is 7, break out of the loop. If the number is even, continue to the next iteration without printing it. Otherwise, print the odd number.