Loops are fundamental in JavaScript—they help you execute a block of code repeatedly. But with different types of loops available, it's important to know when and how to use each one effectively.
1. for
Loop
When to use:
- When you know exactly how many times you need to iterate.
- Ideal for arrays when you need the index.
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
2. while
Loop
When to use:
- When the number of iterations is unknown and depends on a condition.
- Useful for reading streams or waiting for a condition to be met.
Example:
let count = 0;
while (count < 5) {
console.log(count); // 0, 1, 2, 3, 4
count++;
}
3. do...while
Loop
When to use:
- When you want the loop to run at least once, even if the condition is false.
Example:
let x = 0;
do {
console.log(x); // 0 (runs once even if condition is false)
x++;
} while (x < 0);
4. for...of
Loop
When to use:
- When iterating over arrays, strings, or other iterable objects.
- Cleaner syntax when you don’t need the index.
Example:
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num); // 1, 2, 3
}
5. for...in
Loop
When to use:
- When iterating over object properties (keys).
- Avoid using for arrays (use
for...of
instead).
Example:
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]); // "a 1", "b 2"
}
6. Array.forEach()
When to use:
- When you want to execute a function on each array element.
- Doesn’t return a new array (unlike
map()
).
Example:
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2)); // 2, 4, 6
Key Takeaways
✅ Use for
when you know the iteration count.
✅ Use while
/do...while
for condition-based looping.
✅ Use for...of
for arrays and iterables.
✅ Use for...in
for object properties (but check hasOwnProperty
).
✅ Use forEach
for simple array iteration (but note it doesn’t break early).
Which loop do you use most often? Let me know in the comments! 🚀
Top comments (0)