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
}
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
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