Spex3
    

JavaScript Loops πŸ”„


    

    

JavaScript Loops πŸ”„
Loops execute a block of code multiple times until a condition is met.

1️⃣ Types of Loops
Loop Type Use Case
for loop Runs a block of code a fixed number of times.
while loop Runs a block while a condition is true.
do...while loop Runs at least once, then continues while the condition is true.

2️⃣ for Loop (Fixed Repetitions)
Used when we know how many times to run the loop.

βœ… Basic for Loop Structure


for (initialization; condition; increment/decrement) {
// Code to run
}


βœ… Example: Counting from 1 to 5

for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5


βœ… Looping Through an Array

let fruits = ["Apple", "Banana", "Cherry"];

for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Cherry

3️⃣ while Loop (Condition-Based Repetitions)
Used when we don’t know the number of repetitions beforehand.

βœ… Basic while Loop Structure

while (condition) {
// Code to run
}


βœ… Example: Count Until 5

let count = 1;

while (count <= 5) {
console.log("Count:", count);
count++; // Increment count
}
// Output: 1, 2, 3, 4, 5


βœ… Example: Running Until User Input

let password = "";

while (password !== "secret") {
password = prompt("Enter the password:");
}

console.log("Access Granted!");

πŸ“Œ Use Case: Keep asking until the user enters "secret".

4️⃣ do...while Loop (Runs At Least Once)
Runs the block at least once, even if the condition is false.

βœ… Basic do...while Loop Structure

do {
// Code to run
} while (condition);


βœ… Example: Ask for a Number (At Least Once)

let number;

do {
number = prompt("Enter a number greater than 10:");
} while (number <= 10);

console.log("You entered:", number);


πŸ“Œ Difference from while loop:

do...while runs once before checking the condition.

while checks the condition before running the loop.

5️⃣ Breaking and Skipping Loops
βœ… break (Exit the Loop)
 
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Stops the loop when i = 5
}
console.log(i);
}
// Output: 1, 2, 3, 4


βœ… continue (Skip to Next Iteration)

for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips 3 and moves to next iteration
}
console.log(i);
}
// Output: 1, 2, 4, 5


6️⃣ Summary: When to Use Each Loop
βœ… Use for when you know how many times to loop.
βœ… Use while when you don’t know how many times but have a condition.
βœ… Use do...while when the code must run at least once.


    Date: 2025-03-29 00:00:00.000000