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.
for (const item of items) { console.log(item); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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...ofgives values;for...ingives property names. Mixing them up is a common mistake. - Early exit.
break,returnor a thrown error closes the iterator by calling itsreturn()method, letting generators runfinallyblocks.continueskips to the next value. constis fine because each iteration gets a new binding.- Awaiting inside.
awaitworks inside the body in an async function, running iterations one after another. For async iterables usefor await...of. - Live collections. Arrays are read by index as the loop proceeds, so items you append during the loop are visited; a
Setvisits items added while iterating, andMapentries added during the loop are visited too. - Need an index? Use
array.entries()as shown, or a classicforloop. - Array-like but not iterable objects (
{ length: 2, 0: "a", 1: "b" }) needArray.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.