04. for-of loop

for-of is a new loop in ES6 that replaces both for-in and forEach() that supports the new iteration protocol.

  • Use it to loop over iterable objects (Arrays, strings, Maps, Sets).

  • for-of goes through the items of iterable and assigns them, one at a time, to the loop variable, before it executes the body.

  • The scope of loop variable is the loop, it only exists inside it.

  • break and continue work inside for-of loops:

// iterate over array
const iterable = ["a", "b"];
for (const x of iterable) {
  console.log(x);
}

// Iterate over map
const map = new Map([
  [false, "no"],
  [true, "yes"]
]);
for (const [key, value] of map) {
  console.log(`${key} => ${value}`);
}

The operand of the of clause must be iterable:

// Array-like, but not iterable!
const arrayLike = { length: 2, 0: "a", 1: "b" };

for (const x of arrayLike) {
  // TypeError
  console.log(x);
}

for (const x of Array.from(arrayLike)) {
  // OK
  console.log(x);
}

Last updated