The Symbol.iterator well-known symbol specifies the default iterator for an object. Used by for...of.
Property attributes of Symbol.iterator
| |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
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:
Array.prototype[@@iterator]()TypedArray.prototype[@@iterator]()String.prototype[@@iterator]()Map.prototype[@@iterator]()Set.prototype[@@iterator]()See also Iteration protocols for more information.
We can make our own iterables like this:
var myIterable = {}
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable] // [1, 2, 3]
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
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Symbol.iterator' in that specification. | Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Symbol.iterator' in that specification. | Draft |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 43 | Yes | 36 | No | 30 | 10 |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 36 | Yes | 10 | Yes |
| Server | |
|---|---|
| Node.js | |
| Basic support | 0.12 |
Array.prototype[@@iterator]()TypedArray.prototype[@@iterator]()String.prototype[@@iterator]()Map.prototype[@@iterator]()Set.prototype[@@iterator]()
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator