Coding

JavaScript For Loop: Syntax, Examples and for...of vs for...in

A JavaScript for loop repeats a block of code while a condition is true: for (let i = 0; i < 5; i++) { ... } runs the body five times, with i going from 0 to 4. The same keyword also has two shorter forms, for...of for values of an array or other iterable and for...in for the keys of an object.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

Example output: 0 1 2 3 4, one number per line.

JavaScript for loop syntax

The classic for statement has three expressions inside the parentheses, separated by semicolons, followed by the statement to repeat (usually a block in braces):

for (initialization; condition; afterthought) {
  // body
}
PartWhen it runsTypical use
initializationonce, before the loop beginslet i = 0
conditionbefore every iteration; the body runs only if it is truei < 5
afterthoughtat the end of every iteration, before the condition is checked againi++

All three parts are optional. MDN documents what happens when you leave them out: a missing initialization simply does nothing, a missing condition is always true, and a missing afterthought does nothing. Leaving out the condition means the loop only ends if the body calls break, so the two forms below are equivalent:

for (let i = 0; ; i++) {
  console.log(i);
  if (i > 3) break;
}

for (let i = 0; i <= 4; i++) {
  console.log(i);
}

MDN suggests a while loop when you are not using all three positions, because it states the intent more clearly.

Common for loop examples

Loop through an array by index

Start at 0, stop before array.length. Using < rather than <= avoids the classic off-by-one error, because the last valid index is length - 1.

const fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}

Example output:

0 apple
1 banana
2 cherry

Count down

Start high, test against a lower bound and decrement. This is handy for removing items from an array while looping, since deleting from the end does not shift the indexes you have yet to visit.

for (let i = 3; i > 0; i--) {
  console.log(i);
}
console.log("liftoff");

Example output: 3, 2, 1, then liftoff.

Step by more than one

The afterthought can be any expression, so i += 2 visits every second number:

for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}

Example output: 0 2 4 6 8 10.

Sum numbers

const prices = [4.5, 10, 2.25];
let total = 0;

for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}
console.log(total);

Example output: 16.75. Declare total outside the loop. A variable declared with let inside the body is created again on every iteration and is gone when the loop ends.

Nested loops

A loop inside a loop runs the inner one completely for every pass of the outer one. A 3 by 3 multiplication table therefore runs the body 9 times:

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += row * col + " ";
  }
  console.log(line);
}

Example output:

1 2 3
2 4 6
3 6 9

break, continue and labels

Two statements change the normal flow. Per MDN, break stops the loop and continues with the first statement after it. continue stops the current iteration, runs the afterthought, then re-checks the condition.

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue;   // skip even numbers
  if (i > 7) break;           // stop entirely after 7
  console.log(i);
}

Example output: 1 3 5 7.

A plain break only leaves the innermost loop. To leave an outer loop from inside an inner one, put a label in front of the outer loop and name it in the break:

search: for (let row = 0; row < 3; row++) {
  for (let col = 0; col < 3; col++) {
    if (row * col === 2) {
      console.log("found at", row, col);
      break search;
    }
  }
}

Example output: found at 1 2. A label must enclose the break that uses it, otherwise JavaScript raises a SyntaxError.

for...of: loop over values

When you want the items and not the index, for...of is shorter and cannot go off by one. It works on any iterable: MDN lists Array, String, Map, Set, NodeList, the arguments object, generators and user-defined iterables.

for (const fruit of ["apple", "banana", "cherry"]) {
  console.log(fruit);
}

for (const [key, value] of new Map([["a", 1], ["b", 2]])) {
  console.log(key, value);
}

for (const char of "boo") {
  console.log(char);
}

Use const for the loop variable when you do not reassign it; each iteration gets a new binding. break and continue work the same way as in the classic loop.

If you need the index as well, call entries() on the array and destructure each pair:

for (const [index, fruit] of ["apple", "banana"].entries()) {
  console.log(index, fruit);
}

Plain objects are not iterable, so for (const x of {a: 1}) throws a TypeError. Convert the object to an array first with Object.entries():

const stock = { apples: 3, pears: 0 };

for (const [name, count] of Object.entries(stock)) {
  console.log(name, count);
}

for...in: loop over object keys

for...in visits the enumerable, string-keyed properties of an object, including ones inherited through its prototype chain. It gives you the keys, as strings:

const user = { name: "Sam", role: "admin" };

for (const key in user) {
  console.log(key, user[key]);
}

Example output: name Sam then role admin. Because inherited properties are included, MDN suggests guarding with Object.hasOwn(obj, key) or using Object.keys() when only the object's own properties matter. MDN also advises against for...in on arrays: the indexes arrive as the strings "0", "1" and so on, any extra enumerable property on the array shows up too, and holes in sparse arrays are skipped.

Which loop should you use?

You wantUse
to count, or step by a custom amountclassic for
every value of an array, string, Map or Setfor...of
the index and the value of an arrayfor...of with .entries(), or classic for
the keys of a plain objectObject.keys(), Object.entries(), or for...in with an own-property check
to stop early or skip itemsany for form, with break or continue

forEach is a method rather than a loop statement. Its callback is a function, so break and continue are not allowed inside it, and a break there is a SyntaxError. If you need to stop early, use for...of.

The let vs var trap inside loops

This is the most common surprise with the classic loop. A variable declared with var is function-scoped, so every iteration shares the same one. A let in the initialization gets a new binding for each iteration. MDN's example schedules a callback inside each pass:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// logs 3, 3, 3

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// logs 0, 1, 2

With var, all three callbacks run after the loop has finished and see the final value, 3. Use let or const in new code and the problem does not arise.

Infinite loops and the stray semicolon

Two mistakes cause most hung scripts. The first is a condition that never becomes false, such as forgetting the afterthought: for (let i = 0; i < 5;) never changes i, so it runs forever. The second is a semicolon straight after the closing parenthesis. MDN points out that a semicolon there is an empty statement, which becomes the loop body, and the block that follows then runs once, after the loop:

for (let i = 0; i < 3; i++);   // empty body
{
  console.log("runs once, with i out of scope");
}

MDN uses an empty body on purpose in one example and notes the semicolon is mandatory there, because otherwise the next line becomes the body. Outside that situation, a stray semicolon is a bug, and a linter will usually flag it.

Looping with async code

Inside an async function, await works in the body of a for or for...of loop, so the iterations run one after another. That is the right choice when each step depends on the last. For independent work, start the promises first and wait for them together. See JavaScript async/await explained for sequential versus parallel awaits, and why forEach does not wait.

Frequently asked questions

Can a JavaScript for loop run with no condition?
Yes. If the condition is omitted it is always treated as true, so the loop never stops by itself. MDN says you must make sure to break out of the body, for example with an if statement and break, or the loop is infinite.
Why does my for loop with var print the same number every time inside setTimeout?
A var declaration is function-scoped, so every callback shares one variable, and by the time the callbacks run the loop has finished. MDN's example with var logs 3, 3, 3 for a loop that counts to 3. Declaring the counter with let creates a fresh binding per iteration and logs 0, 1, 2.
Does for...of work on a plain object?
No. for...of needs an iterable, and a plain object does not define Symbol.iterator, so the loop throws a TypeError. Loop over Object.keys(obj), Object.values(obj) or Object.entries(obj) instead, which return arrays.
Can I use break inside forEach?
No. The callback passed to forEach is a function, and MDN states that break cannot be used across a function boundary: it is a SyntaxError. Use a for or for...of loop when you need to stop early, or the some() and every() array methods.

Sources