JavaScript: for-of Loop

By Xah Lee. Date: . Last updated: .

New in JS2015.

for (variable of iterable) {…}

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

Iterate Over Array

for-of loop on Array Object

// for-of loop on array
for (let x of [3, 4, 5]) console.log(x); // prints 3 4 5

Iterate over array with index and value

Iterate over array with index and value. By Destructuring Assignment and Array.prototype.entries.

let rr = ["a", "b", "c"];

// loop over array with index and value
for (let [i, x] of rr.entries()) {
  console.log(i, x);
}

// prints

// 0 a
// 1 b
// 2 c

Iterate Over Characters in String

When used on string, it goes thru each char, not String Code Unit . This fixed a long time JavaScript problem.

// 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 Over Members in a Set Object

// 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 over Map object

JavaScript Iterable 🌟

JavaScript Loop, Iteration

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc