JS: for-of Loop

By Xah Lee. Date: . Last updated: .

New in ES2015.

for (variable of iterable_object) { … }

The for-of loop is a syntax that lets you go thru array's values, or any “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?

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

for (let value in 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, List Properties

Iterate Array

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

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

〔►see JS: Array Object

Iterate String

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

〔►see JS: String Code Unit vs Code Point

// 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

Iterate 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

Iterate Map

〔►see JS: Iterate Over Map Object

for-in Loop

See also: JS: for-in Loop

Reference

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

ECMAScript 2015 §Control Abstraction Objects#sec-iteration

Iterable / Iterator / Generator Topic

  1. JS: Interface
  2. JS: Iterable
  3. JS: Iterator
  4. JS: for-of Loop
  5. JS: Generator Function
  6. JS: Generator
Like what you read? Buy JavaScript in Depth