Loops let you repeat code while a condition is true, or over a list of items. JavaScript supports several loop types for different use cases.
JavaScript Loops
1) for Loop
Runs a block a fixed number of times. Syntax: for(initialization; condition; update).
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
2) while Loop
Repeats while the condition is true. The condition is checked before each iteration.
let n = 1;
while (n <= 3) {
console.log("Number: " + n);
n++;
}
3) do...while Loop
Runs the block at least once, then repeats while the condition is true.
let k = 1;
do {
console.log("k = " + k);
k++;
} while (k <= 3);
4) for...of Loop
Loops over values of an iterable (arrays, strings, etc.).
const colors = ['red', 'green', 'blue'];
for (const c of colors) {
console.log(c);
}
5) for...in Loop
Loops over keys (property names) in an object.
const user = {name: 'Sonu', age: 20};
for (let key in user) {
console.log(key + ": " + user[key]);
}
Tip: Use
for...of for arrays/strings, for...in for object keys. Always make sure loops can end, otherwise you get an infinite loop.