Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Symbol.iterator

A special key that makes an object iterable in for...of and spread.

Available since: ES2015

Syntax

obj[Symbol.iterator] = function* () { … }

Examples

Your own iterable object:

const range = {
  from: 1,
  to: 4,
  *[Symbol.iterator]() {
    for (let i = this.from; i <= this.to; i++) yield i;
  },
};
 
console.log([...range].join(', '));
 
for (const n of range) {
  if (n > 2) break;
  console.log(n);
}

Output:

1, 2, 3, 4
1
2

An iterator by hand — the next() method:

const iterator = ['a', 'b'][Symbol.iterator]();
 
console.log(iterator.next());
console.log(iterator.next().value);
console.log(iterator.next().done);

Output:

{
  "value": "a",
  "done": false
}
b
true

Notes

An iterator is an object with a next() method that returns { value, done }. Arrays, strings, Maps and Sets are already iterable; plain objects are not.

See also

  • function* — A generator function: produces values one at a time with yield.
  • for...of — Loops over the values of arrays, strings, Maps, Sets and other iterables.
  • Spread syntax — Three dots spread an array or object into separate items.
  • Symbol — Creates a unique value — for example, a key that never clashes with others.

In the tutorial

  • Iterators and generators — How for...of works in JavaScript: iterable objects, iterators and the next method, generator functions with yield, and your own iterable object.

Thanks for reading!

Donate to the site — we work hard for you.