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,forloops,whileloops, anddo-whileloops. - 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 / elseStatement:- Executes a block of code if a specified condition is true.
else ifallows checking multiple conditions.elseprovides 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.
switchStatement:- Evaluates an expression and matches its value against a series of
caseclauses. - Executes statements associated with the first matching
case. breakis crucial to prevent “fall-through” to subsequent cases.defaultclause 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 } - Evaluates an expression and matches its value against a series of
-
3.
forLoop:- 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...ofloop: 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...inloop: 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.
whileLoop:- 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...whileLoop:- Similar to a
whileloop, 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); - Similar to a
-
breakandcontinueStatements:break: Exits the current loop (for,while,do-while) orswitchstatement 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:
if/else: Write a program that checks if a number is positive, negative, or zero and prints the result.switch: Create a variablefruitand assign it a fruit name (e.g., “apple”, “banana”, “orange”). Use aswitchstatement to print a message about the fruit (e.g., “Apples are red.”, “Bananas are yellow.”). Include adefaultcase for unknown fruits.forloop: Print the numbers from 1 to 10 using aforloop.for...ofloop: Create an array of your favorite hobbies. Use afor...ofloop to print each hobby.whileloop: Write awhileloop that prints numbers from 5 down to 1.do...whileloop: Simulate a dice roll. Use ado...whileloop 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!”.break/continue: Write aforloop that iterates from 1 to 10. If the number is 7,breakout of the loop. If the number is even,continueto the next iteration without printing it. Otherwise, print the odd number.