Loops in javascript
Loops repeatedly execute code while a condition holds. Use for and while for general loops, do...while when you must run the body at least once, for...of to loop over iterable values (arrays, strings, maps), and for...in to loop over object keys. Array methods like forEach, map, filter, and reduce are declarative alternatives to manual loops.
Example
// Classic for
for (let i = 0; i < 3; i++) {
console.log("for:", i);
}
// while
let n = 0;
while (n < 3) {
console.log("while:", n++);
}
// do...while (runs at least once)
let k = 5;
do {
console.log("do while:", k);
k++;
} while (k < 3);
// for...of (values)
for (const value of [10, 20, 30]) {
console.log("of:", value);
}
// for...in (keys)
const user = { name: "Punam", age: 25 };
for (const key in user) {
console.log(key, user[key]);
}This shows the main loop forms and when they run: for/while depend on a condition, do...while runs at least once, for...of iterates values, and for...in iterates keys on an object.