for...of

Walks the successive values of an iterable object: an array, a string, a Map, a Set, and others.

On this page

Example

#
JavaScript
const skills = ['HTML', 'CSS', 'JavaScript']

for (const skill of skills) {
  console.log(`Learning: ${skill}`)
}
Console
Learning: HTML
Learning: CSS
Learning: JavaScript

Definition and usage

#

On every turn, a for...of loop hands you the next value from an iterable object. You don’t have to manage a counter or reach for an element by index, so the code is shorter and less prone to off-by-one errors.

It works with arrays, strings (character by character, without splitting emoji in half), Map and Set objects, querySelectorAll() lists, and generators. A plain object {} is not iterable, so you walk its contents with Object.keys(), Object.values(), or Object.entries().

Unlike forEach(), for...of lets you use break, continue, return, and await. When you also need the index, use array.entries() with destructuring: for (const [index, value] of array.entries()).

Syntax

#
Syntax
for (const element of iterable) {
  // statements
}

More examples

#
Index and value via entries()
JavaScript
const tasks = ['Variables', 'Loops', 'Functions']

for (const [index, task] of tasks.entries()) {
  console.log(index, task)
}
Console
0 Variables
1 Loops
2 Functions
An object via Object.entries()
JavaScript
const scores = { Emma: 120, Jack: 95 }

for (const [name, points] of Object.entries(scores)) {
  console.log(`${name} has ${points} pts`)
}
Console
Emma has 120 pts
Jack has 95 pts
A string, character by character
JavaScript
const word = 'Code👾'

for (const char of word) {
  console.log(char)
}

console.log(word.length)
Console
C
o
d
e
👾
6

for...of walks whole Unicode characters, so the emoji is a single element, even though length counts it as 2.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • for...of gives you values, for...in gives you keys. For arrays, you almost always want for...of.
  • With await inside the loop, the operations run one after another. To run them in parallel, collect the promises into an array and use Promise.all().
  • Declare the loop variable with const. Every turn gets a new variable, so an accidental overwrite reports an error right away.

Related entries

#

Spotted a mistake or missing an example? Write to us.