JavaScript Loops
Loops let you repeat a block of code. JavaScript has several kinds, each suited to different situations.
for loop
The for loop is the classic option when you know in advance how many times you want to repeat.
It takes three expressions inside the parentheses, separated by semicolons:
- An initialiser that runs once at the start.
- A condition that is checked before each iteration. The loop keeps running while this is true.
- An update that runs after each iteration.
for (let i = 0; i < 3; i++) {
console.log(i);
}
// 0
// 1
// 2
The loop starts at 0, runs while i < 3, and increments after each pass. So i takes the values 0, 1, and 2 (three iterations total).
Looping through an array with a for loop
const cities = ['London', 'Copenhagen', 'Tokyo'];
for (let i = 0; i < cities.length; i++) {
console.log(`I would love to visit ${cities[i]}`);
}
This works, but for...of (covered below) is cleaner when you do not need the index.
while loop
The while loop runs as long as a condition is true. Use it when you do not know in advance how many iterations you need.
let attempts = 0;
while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts++;
}
// Attempt 1
// Attempt 2
// Attempt 3
Make sure the condition will eventually become false, or you will create an infinite loop that freezes the page.
do…while loop
The do...while loop is similar to while, but the body runs at least once before the condition is checked.
let count = 0;
do {
console.log(`Count is ${count}`);
count++;
} while (count < 3);
// Count is 0
// Count is 1
// Count is 2
Use do...while when you need to run the body at least once regardless of the condition (for example, prompting a user for input until they give a valid answer).
for…of loop
for...of is the modern way to loop over arrays and other iterable values (strings, Sets, Maps). It gives you the value directly without needing an index.
const fruits = ['apple', 'banana', 'mango'];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// mango
You can also iterate over a string character by character:
for (const char of 'hello') {
console.log(char);
}
// h
// e
// l
// l
// o
for…of vs a regular for loop: Use for...of when you want each value and do not need the index. Use a regular for loop when you need the index, or when you want to start at a position other than zero.
// Need the index? Use for loop or entries()
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}
// 0: apple
// 1: banana
// 2: mango
for…in loop
for...in iterates over the keys of an object.
const person = {
name: 'Anna',
age: 28,
city: 'Copenhagen',
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Anna
// age: 28
// city: Copenhagen
Do not use for...in on arrays. It iterates over the keys (which are string indices like '0', '1', '2'), not the values, and it can also pick up inherited properties you did not expect.
const numbers = [10, 20, 30];
// Wrong way to loop an array
for (const key in numbers) {
console.log(key); // '0', '1', '2' (string keys, not values)
}
// Right way
for (const num of numbers) {
console.log(num); // 10, 20, 30
}
Loop control: break and continue
continue
continue skips the rest of the current iteration and moves on to the next.
const numbers = [1, 2, 3, 4, 5, 6];
const odds = [];
for (const n of numbers) {
if (n % 2 === 0) continue; // skip even numbers
odds.push(n);
}
console.log(odds); // [1, 3, 5]
break
break exits the loop entirely.
const names = ['Alice', 'Bob', 'Charlie', 'Dave'];
for (const name of names) {
if (name === 'Charlie') break; // stop when we find Charlie
console.log(name);
}
// Alice
// Bob
Common mistakes
Using for...in on an array: This gives you the string index keys, not the values. Use for...of for arrays.
Off-by-one errors: A condition of i < array.length is correct for zero-indexed arrays. Using i <= array.length will try to access an index that does not exist and return undefined.
Functional alternatives
For arrays specifically, methods like forEach(), map(), and filter() are often cleaner than explicit loops. See forEach()
and map()
for examples.