fbpx

Control Flow in JavaScript: If Statements and Loops

Control flow structures in JavaScript empower developers to dictate the flow of program execution. If statements allow for conditional execution, and loops facilitate repetitive tasks. Let’s explore how if statements and loops are employed to manage control flow in JavaScript.

1. If Statements:

If statements enable the execution of code blocks conditionally based on a specified condition.

let temperature = 25;

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 cold day.");
}

2. Switch Statement:

Switch statements provide an alternative to if statements when dealing with multiple possible conditions.

let dayOfWeek = "Monday";

switch (dayOfWeek) {
  case "Monday":
    console.log("It's the start of the week.");
    break;
  case "Friday":
    console.log("Weekend is almost here!");
    break;
  default:
    console.log("It's a regular day.");
}

3. Loops:

Loops are used to repeatedly execute a block of code as long as a specified condition is true.

a. For Loop:

The for loop is commonly used when the number of iterations is known.

for (let i = 0; i < 5; i++) {
  console.log("Iteration: " + i);
}

b. While Loop:

The while loop continues executing as long as the specified condition is true.

let count = 0;

while (count < 3) {
  console.log("Count: " + count);
  count++;
}

c. Do-While Loop:

The do-while loop is similar to the while loop, but it guarantees the execution of the block at least once.

let number = 5;

do {
  console.log("Number: " + number);
  number--;
} while (number > 0);

4. Break and Continue:

a. Break Statement:

The break statement terminates the execution of a loop.

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    console.log("Breaking the loop at i = 5.");
    break;
  }
  console.log("Iteration: " + i);
}

b. Continue Statement:

The continue statement skips the current iteration and proceeds to the next one.

for (let i = 0; i < 5; i++) {
  if (i === 2) {
    console.log("Skipping iteration at i = 2.");
    continue;
  }
  console.log("Iteration: " + i);
}

5. For…In and For…Of:

a. For…In Loop:

The for…in loop iterates over the properties of an object.

let person = {
  name: "Alice",
  age: 28,
  job: "Developer",
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}

b. For…Of Loop:

The for…of loop iterates over iterable objects like arrays.

let colors = ["red", "green", "blue"];

for (let color of colors) {
  console.log(color);
}

Understanding and effectively using control flow structures is essential for creating dynamic and responsive JavaScript applications. These structures enable developers to manage the logical flow of their code, make decisions based on conditions, and execute repetitive tasks efficiently. Mastering if statements and loops is foundational to becoming a proficient JavaScript developer.