JavaScript: for-of Loop (ES2015)

By Xah Lee. Date: . Last updated: .

The for-of loop is a syntax that lets you go thru array's values, or any “iterable” object's values.

Standard iterable objects include: string, array, set, map. 〔➤see JavaScript: Iterable (ES2015)

Syntax is:

for (variable of iterable_object) { … }

Iterating Array

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

for (let x of aa) {
    console.log(x);
} // prints 3 4 5

〔➤see JavaScript: Array Object and Properties

Iterating Set

// for-of loop over set object

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

for (let v of mySet) {
  console.log(v);
}

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

Iterating Map

// for-of loop over map object

let myDictionary = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let pair of myDictionary) {
  console.log(pair);
}
// prints
// [ 'a', 1 ]
// [ 'b', 2 ]
// [ 'c', 3 ]

// using key and value
for (let [k, v] of myDictionary) {
  console.log(k, v);
}
// prints
// a 1
// b 2
// c 3

Iterating String

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

〔➤see JavaScript String is 16 Bits Byte Sequence

// 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") {
    console.log(x);
}

// prints

// a
// b
// 😸
// d

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

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

for (let value in iterable) {…} work with iterable object only, and iterate the value of properties. Does not go up to the prototype chain. Order is determined by the iterable's [Symbol.iterator] method.

〔➤see JavaScript: Iterable (ES2015)

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

〔➤see JavaScript: Access/List Properties

ES2015 §ECMAScript Language: Statements and Declarations#sec-for-in-and-for-of-statements

ES2015 §Control Abstraction Objects#sec-iteration
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.