JavaScript Loops Explained with Examples
Loops in JavaScript are used to repeat a block of code multiple times—until a certain condition is false. They are essential for iterating over arrays, objects, and performing repetitive tasks.
1. for Loop – Best for known iteration count
Syntax:
for (initialization; condition; increment) {
// code block
}
Example:
for (let i = 1; i <= 3; i++) {
console.log("Count: " + i);
}
Output
Count: 1
Count: 2
Count: 3
2. while Loop – Runs while the condition is true
Example:
let i = 1;
while (i <= 3) {
console.log("While loop count: " + i);
i++;
}
Output
While loop count: 1
While loop count: 2
While loop count: 3
While loop count: 2
While loop count: 3
3. do...while Loop – Runs at least once, then checks condition
Example:
let i = 1;
do {
console.log("Do While count: " + i);
i++;
} while (i <= 3);
Output
Do While count: 1
Do While count: 2
Do While count: 3
Do While count: 2
Do While count: 3
4. for...of Loop – Loops over iterables like arrays
Example:
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Output
Apple
Banana
Cherry
Banana
Cherry
5. for...in Loop – Loops over object keys
Example:
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output
name: Alice
age: 25
age: 25
Summary Table – JavaScript Loops
Loop Type | Use Case | Iterates Over |
---|---|---|
for | Known number of iterations | Counters/indexes |
while | Unknown count, condition controlled | Conditions |
do...while | Must run at least once | Conditions |
for...of | Iterate over arrays/strings | Iterables (Array, Set) |
for...in | Iterate over object properties | Object keys |