Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The for...of statement

Reference for the JavaScript for...of statement: looping over arrays, strings, Maps, Sets and generators, destructuring, entries() and early exit.

The for...of statement loops over the values produced by an iterable: arrays, strings, Map, Set, typed arrays, arguments, DOM collections such as NodeList, generators and any object that implements the iterator protocol. It is the most readable way to visit every item when you do not need the index.

Plain objects are not iterable, so for (const x of { a: 1 }) throws a TypeError. Loop over Object.entries(obj) instead.

JavaScript
for (const item of items) {
  console.log(item);
}

Try it

JS Arrays, strings, Maps and Sets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Generators, early exit and errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
for (variable of iterable) {
  statement
}
Part Description
variable A binding (const, let, var) or destructuring pattern, or an assignment target, receiving each value.
iterable An expression whose value has a Symbol.iterator method.

Exceptions: a TypeError if the value is not iterable (including null and undefined).

Usage notes

  • Values, not keys. for...of gives values; for...in gives property names. Mixing them up is a common mistake.
  • Early exit. break, return or a thrown error closes the iterator by calling its return() method, letting generators run finally blocks. continue skips to the next value.
  • const is fine because each iteration gets a new binding.
  • Awaiting inside. await works inside the body in an async function, running iterations one after another. For async iterables use for await...of.
  • Live collections. Arrays are read by index as the loop proceeds, so items you append during the loop are visited; a Set visits items added while iterating, and Map entries added during the loop are visited too.
  • Need an index? Use array.entries() as shown, or a classic for loop.
  • Array-like but not iterable objects ({ length: 2, 0: "a", 1: "b" }) need Array.from() first.
  • Performance. Fast enough for almost all code; in very hot paths measure against an indexed loop.

Browser support

Supported in every current browser and Node.js; part of the language since ES2015.