JavaScript: for-of Loop

By Xah Lee. Date: . Last updated: .

New in JS2015.

for (variable of iterable) {body}

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 (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 xx = ["a", "b", "c"];

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

/* [
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 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 xx = new Set([3, 4, 5]);

for (let v of xx) {
  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