W3cubDocs

/JavaScript

Symbol.iterator

The well-known Symbol.iterator symbol specifies the default iterator for an object. Used by for...of.

Description

Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.

Some built-in types have a default iteration behavior, while other types (such as Object) do not. The built-in types with a @@iterator method are:

See also Iteration protocols for more information.

Property attributes of Symbol.iterator
Writable no
Enumerable no
Configurable no

Examples

User-defined iterables

We can make our own iterables like this:

var myIterable = {}
myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
};
[...myIterable] // [1, 2, 3]

Or iterables can be defined directly inside a class or object using a computed property:

class Foo {
  *[Symbol.iterator] () {
    yield 1;
    yield 2;
    yield 3;
  }
}

const someObj = {
  *[Symbol.iterator] () {
    yield 'a';
    yield 'b';
  }
}

[...new Foo] // [ 1, 2, 3 ]
[...someObj] // [ 'a', 'b' ]

Non-well-formed iterables

If an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior:

var nonWellFormedIterable = {}
nonWellFormedIterable[Symbol.iterator] = () => 1
[...nonWellFormedIterable] // TypeError: [] is not a function

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
iterator 43 12 36 No 30 10
Mobile
Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
iterator 43 43 36 30 10 4.0
Server
Node.js
iterator 0.12

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator