Loops are fundamental for processing collections and repeating actions. **for** is best for indexed iterations. **for...of** iterates iterable values (arrays, strings, Sets). **for...in** iterates object keys. **while** loops when the count is unknown. **Array methods** (map, forEach, filter) are often cleaner than for loops.
1Understanding Loops
Loops are fundamental for processing collections and repeating actions. for is best for indexed iterations. for...of iterates iterable values (arrays, strings, Sets). for...in iterates object keys. while loops when the count is unknown. Array methods (map, forEach, filter) are often cleaner than for loops.
Prefer for...of over for...in for arrays. for...in also picks up inherited prototype properties.
// Classic for loop
for (let i = 0; i < 5; i++) {
process.stdout.write(i + ' ');
}
// Output: 0 1 2 3 4
// for...of (preferred for arrays)
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}2Practical Example
Here is a real-world application of Loops showing how it is used in production JavaScript code.
// for...in for objects
const car = { make: 'Toyota', year: 2022 };
for (const key in car) {
console.log(`${key}: ${car[key]}`);
}3Best Practices
Follow these guidelines when working with Loops:
1. Use for...of for arrays and iterables
2. Use for...in only for plain objects
3. Avoid infinite loops — ensure the condition changes
Tip: Prefer for...of over for...in for arrays. for...in also picks up inherited prototype properties.
// Classic for loop
for (let i = 0; i < 5; i++) {
process.stdout.write(i + ' ');
}
// Output: 0 1 2 3 4
// for...of (preferred for arrays)
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}