Loops (for, while, do...while)
JavaScript offers several looping structures to help execute code repeatedly based on certain conditions.
1. for Loop
The for
loop is one of the most commonly used loops. It's ideal when you know how many times you need to execute a block of code. It has three parts: initialization, condition, and increment/decrement.
for (let i = 0; i < 5; i++) {console.log(i);}
Explanation:
Initialization (
let i = 0
): Sets the starting point.Condition (
i < 5
): Loop runs as long as this is true.Increment/Decrement (
i++
): Updates the variable after each loop.Example Use Case: Looping through an array
const fruits = ["apple", "banana", "cherry"];for (let i = 0; i < fruits.length; i++) {console.log(fruits[i]);}
2. while Loop
The while
loop executes as long as the condition is true
. This loop is helpful when you don't know the exact number of iterations in advance.
let count = 0;while (count < 5) {console.log(count);count++;}
Explanation:
The condition (
count < 5
) is evaluated before each loop.If true, the code block runs.
Once the condition is false, the loop stops.
Example Use Case: User input validation
let password;while (password !== "secret") {password = prompt("Enter the correct password:");}console.log("Access granted");
3. do...while Loop
The do...while
loop is similar to the while
loop but guarantees that the code block runs at least once, as the condition is checked after the loop body.
let num = 0;do {console.log(num);num++;} while (num < 5);
Explanation:
Runs the code in the
do
block once, then checks thewhile
condition.If the condition is true, it loops; if false, it exits.
Example Use Case: Executing a block once before a condition check
let answer;do {answer = prompt("Type 'yes' to continue:");} while (answer !== "yes");console.log("Continuing...");
Summary
for
loop: Use when you know the number of iterations.while
loop: Use when the number of iterations is unknown, but a condition is involved.do...while
loop: Use when you need the code to run at least once before condition checking.