Class 9: JavaScript Control Flow
In the previous class, we learned about JavaScript variables, data types, and operators. Now, we'll dive into the core concepts that allow your programs to make decisions and perform repetitive tasks: Control Flow. These are fundamental to writing any meaningful program.
Branching Statements
Branching or Conditional statements allow you to execute different blocks of code based on whether a specified condition is true or false.
if, else if, else
The most common way to make decisions in JavaScript.
let temperature = 28;
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a pleasant day.");
} else {
console.log("It's a bit chilly.");
}
-
The
ifblock executes if its condition istrue. -
If the
ifcondition isfalse, theelse ifcondition is checked. You can have multipleelse ifblocks. -
The
elseblock executes if none of the precedingiforelse ifconditions aretrue.
switch Statement
The switch statement is used to perform different
actions based on different conditions. It's often used as an
alternative to long if...else if chains when
comparing a single variable against multiple possible values.
let day = "Monday";
let activity;
switch (day) {
case "Monday":
activity = "Start work week";
break;
case "Friday":
activity = "Prepare for weekend";
break;
case "Saturday":
case "Sunday": // Multiple cases can share a single block
activity = "Enjoy weekend";
break;
default:
activity = "Mid-week routine";
}
console.log(`Today's activity: ${activity}`);
- The
switchexpression is evaluated once. -
The value of the expression is compared with the values of
each
case. - If there is a match, the associated block of code is executed.
-
break: This keyword exits theswitchstatement once a match is found and executed. Withoutbreak, the code will continue to execute the nextcase(fall-through). -
default: Specifies the code to run if there is no case match. It's optional.
Looping Constructs
Loops are used to execute a block of code repeatedly as long as a certain condition is met. They are essential for processing lists of data or performing tasks multiple times.
for Loop
The for loop is the most common loop. It's used
when you know exactly how many times you want to loop.
for (let i = 0; i < 5; i++) {
console.log("Count:", i);
}
-
Initialization (
let i = 0;): Executed once before the loop starts. -
Condition (
i < 5;): Evaluated before each iteration. Iftrue, the loop continues; iffalse, the loop terminates. -
Increment/Decrement (
i++): Executed after each iteration.
while Loop
The while loop executes a block of code as long as
a specified condition is true. It's suitable when
the number of iterations is not known beforehand.
let count = 0;
while (count < 3) {
console.log("Loop iteration:", count);
count++;
}
do...while Loop
The do...while loop is similar to
while, but it guarantees that the code block will
be executed at least once, because the condition is evaluated
after the block has executed.
let i = 0;
do {
console.log("Do-While iteration:", i);
i++;
} while (i < 0); // Condition is false, but runs once
for...of Loop (for iterable objects)
Introduced in ES6, the for...of loop iterates over
iterable objects (like Arrays, Strings, Maps, Sets, NodeLists,
etc.), providing direct access to the values of the elements.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
const message = "Hello";
for (const char of message) {
console.log(char);
}
for...in Loop (for object properties)
The for...in loop iterates over the enumerable
properties of an object. It's generally not recommended for
iterating over arrays because it iterates over property names
(indexes) and can include inherited properties.
const person = { name: "Alice", age: 30, city: "New York" };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}