JS: for-of Loop

By Xah Lee. Date: . Last updated: .

New in ES2015.

for (variable of iterable) { … }

The for-of loop is a syntax that lets you go thru iterable object's values.

Standard builtin iterable objects include: string, array, set, map. [see JS: Iterable]

What's the difference between for-in loop and for-of loop?

The for-in loop for (let key in object) {…} can be used on any object, and iterates its enumerable string property keys, and will go up to the prototype chain. Order is not guaranteed.

[see JS: for-in Loop]

The for-of loop for (let value of iterable) {…} work with iterable object only. The value that is iterated may or may not be properties. For example, for array object, it goes thru the array values (which is property values) , but for {Map, Set} objects, it iterates their special values, for string object, it iterates thru the characters. Does not go up to the prototype chain. Order is determined by the iterable's [Symbol.iterator] method.

[see JS: Iterable]

(Technically, the value iterated is anything iterable[Symbol.iterator].next() returns.)

[see JS: Access Property]

Iterate Array

// for-of loop on array
let aa = [3,4,5];

for (let x of aa) {
} // prints 3 4 5

[see JS: Array Object]

Here's “for of” loop with index and value:

// for-of loop on array
let aa = ["a", "b", "c"];

for (let [i,x] of aa.entries()) {

// prints
// 0 'a'
// 1 'b'
// 2 'c'

[see JS: Array.prototype.entries]

Iterate String

When used on string, it goes thru each char, not 16 bits unit. This fixed a long time JavaScript problem.

[see JS: Character, Code Unit, Codepoint]

// for of loop thru string.
// in each iteration, the value is a unicode char, not as 16 bits byte sequence

for (let x of "ab😂d") {

// prints

// a
// b
// 😂
// d

Iterate Set

// for-of loop over set object

let mySet = new Set([3,4,5]);

for (let v of mySet) {

// prints
// 3
// 4
// 5

Iterate Map

JS: Iterate Over Map Object

JS Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials