Program Control Statements and loops in JavaScript

Program Control Statements and loops in JavaScript iti

🔁 Program Control Statements and Loops in JavaScript

JavaScript provides various control statements and loops to control the flow of program execution. These allow decisions, repetitions, and conditional logic in web applications.


📌 Control Statements in JavaScript

1. if Statement

Executes a block of code if a specified condition is true.

let age = 18;
if (age >= 18) {
  console.log("Eligible to vote");
}

2. if...else Statement

Executes one block if the condition is true, otherwise another block.

let score = 45;
if (score >= 50) {
  console.log("Pass");
} else {
  console.log("Fail");
}

3. if...else if...else Statement

Checks multiple conditions in sequence.

let marks = 75;
if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 75) {
  console.log("Grade B");
} else {
  console.log("Grade C");
}

4. switch Statement

Used to select one of many code blocks to be executed.

let day = 3;
switch(day) {
  case 1: console.log("Monday"); break;
  case 2: console.log("Tuesday"); break;
  case 3: console.log("Wednesday"); break;
  default: console.log("Invalid day");
}

🔄 Loops in JavaScript

✅ 1. for Loop

Used to execute a block of code a number of times.

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

✅ 2. while Loop

Executes code as long as the condition is true.

let i = 1;
while (i <= 5) {
  console.log("Number: " + i);
  i++;
}

✅ 3. do...while Loop

Executes the code block once before checking the condition.

let i = 1;
do {
  console.log("Value: " + i);
  i++;
} while (i <= 5);

✅ 4. for...of Loop

Used to iterate over iterable objects like arrays.

let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
  console.log(color);
}

✅ 5. forEach() Method

Method used on arrays to run a function on each item.

let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(function(item) {
  console.log(item);
});

🛑 Loop Control Statements

🔸 break Statement

Terminates the loop immediately.

for (let i = 1; i <= 5; i++) {
  if (i == 3) break;
  console.log(i); // prints 1 and 2
}

🔸 continue Statement

Skips the current iteration and continues with the next.

for (let i = 1; i <= 5; i++) {
  if (i == 3) continue;
  console.log(i); // skips 3
}

📋 Summary

  • Control statements like if, else, and switch help in decision-making.
  • Loops like for, while, and do...while repeat actions efficiently.
  • Break exits a loop, and continue skips an iteration.
  • Using loops improves code performance and readability in repetitive tasks.

JavaScript loops and control structures are essential for interactive and logical web development. 🧠💻