for Loop
The classic for loop repeats code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log("Count: " + i);
}
Try it Yourself โ
while Loop
A while loop runs as long as its condition remains true.
let count = 0;
while (count < 3) {
console.log("Tick " + count);
count++;
}
Try it Yourself โ
do...while Loop
A do...while loop always executes its body at least once before checking the condition.
let num = 10;
do {
console.log("Number: " + num);
num++;
} while (num < 10);
// Runs once even though condition is false
Try it Yourself โ
for...in Loop
The for...in loop iterates over enumerable property keys of an object.
const car = { make: "Toyota", model: "Camry", year: 2022 };
for (const key in car) {
console.log(key + ": " + car[key]);
}
Try it Yourself โ
for...of Loop
The for...of loop iterates over iterable values (arrays, strings, etc.).
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
Try it Yourself โ
Looping Backwards
You can decrement the loop counter to traverse an array in reverse.
const items = ["A", "B", "C"];
for (let i = items.length - 1; i >= 0; i--) {
console.log(items[i]);
}
Try it Yourself โ
Nested Loops
Loops inside loops create combinations or grids.
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "* ";
}
console.log(line);
}
Try it Yourself โ
Array Methods as Loops
Methods like forEach, map, and filter are modern alternatives to manual loops.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
numbers.forEach(n => console.log(n * 3));
Try it Yourself โ