Skip to main content

Loops

Syntax for running the same processing repeatedly.

for loops

// A basic for loop
for (let i = 0; i < 5; i++) {
console.log(`Count: ${i}`);
}

A for loop consists of three parts: "the initialization, the condition, and the update."

for (initialization; condition; update) {
// The processing to run repeatedly
}

break and continue

You can break out in the middle of a loop, or skip a particular iteration.

for (let i = 0; i < 10; i++) {
if (i === 5) break; // Break out of the loop when i becomes 5
if (i % 2 === 0) continue; // Skip the rest when i is even
console.log(i); // 1, 3 (stops at 5)
}

while loops

let count = 0;
while (count < 5) {
console.log(`while loop: ${count}`);
count++;
}

do-while loops

Because the condition is evaluated afterward, it runs at least once.

let num = 0;
do {
console.log(`do-while loop: ${num}`);
num++;
} while (num < 5);

for...of loops (for iterable objects)

Used for iterable objects such as arrays and strings.

const colors = ["Red", "Green", "Blue"];

for (const color of colors) {
console.log(color); // Red, Green, Blue
}

When you also want the index

Using entries(), you can extract [index, value] pairs. [index, color] is a way of decomposing an array on the receiving side, which is covered in detail in Arrays.

const colors = ["Red", "Green", "Blue"];

for (const [index, color] of colors.entries()) {
console.log(`${index}: ${color}`); // 0: Red, 1: Green, 2: Blue
}

for...in loops (for objects)

Iterates over an object's properties (keys).

const person = {
name: "Sato",
age: 25,
job: "Engineer"
};

for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
Don't use for...in on arrays

for...in enumerates an object's keys, but it also picks up properties inherited from the prototype, and the index becomes a string rather than a number. For iterating over arrays, use for...of, or higher-order functions such as forEach.

Guidelines for choosing

SyntaxSuited for
forA fixed number of iterations; fine-grained control over the index
whileThe end condition isn't determined by a count
for...ofTaking values one at a time from arrays, strings, and so on
for...inEnumerating an object's keys
  • Functions — Group repeatedly used processing into a "function"