Loops: for, while, and for...of
JavaScript offers several loop styles, each suited to different situations.
for (let i = 0; i < 3; i++) console.log(i);
const fruits = ["apple", "mango", "banana"];
for (const fruit of fruits) console.log(fruit); // values
for (const index in fruits) console.log(index); // keys/indices
let n = 5;
while (n > 0) {
console.log(n);
n--;
}
for...of iterates over the values of any iterable — arrays, strings, Maps, Sets — and is the modern default when you don't need the index. for...in iterates over enumerable property keys and is mainly useful for plain objects; using it on arrays is discouraged because it also picks up inherited or non-index properties.
while and do...while run as long as a condition holds, and are best when the number of iterations isn't known ahead of time — for example, reading from a stream until it ends.