JavaScript Reference ยท Iterators, Generators and Symbols
Symbol.iterator
Reference for Symbol.iterator, the well-known symbol that makes an object iterable for for...of, spread and destructuring, with custom iterable examples.
Symbol.iterator is a well-known symbol used as a method name. An object that has a method under this key is iterable: language features such as for...of, spread ([...x]), array destructuring, Array.from(), new Set(x) and Promise.all(x) call that method to get an iterator and then pull values from it.
Arrays, strings, Map, Set, typed arrays and arguments already have the method. Plain objects do not, which is why for (const x of {}) throws. You add the method to your own classes or objects to make them work with the same syntax.
const iterable = { [Symbol.iterator]() { return { next() { return { value: 1, done: true }; } }; }, };
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
obj[Symbol.iterator]()
| Part | Description |
|---|---|
| Key | Symbol.iterator, a property of the Symbol constructor. It is not writable, enumerable or configurable. |
| Method | A function called with no arguments, with this set to the iterable. |
Return value: an iterator, meaning an object with a next() method that returns { value, done } results. It may also have return() (called when a loop exits early) and throw().
Exceptions: if the method returns something that is not an object, the consuming syntax throws a TypeError. Using an object without the method in for...of or spread also throws a TypeError.
Usage notes
- A generator method is the shortest way.
*[Symbol.iterator]() { yield ... }returns an object that is both an iterator and iterable, and handlesreturn()for you. - Make iterators iterable too. Built-in iterators return themselves from
[Symbol.iterator](), which lets you pass an iterator tofor...ofdirectly. Do the same in hand-written ones if you want that. - Each call should give a fresh iterator when the collection can be traversed repeatedly. Returning a shared, already-advanced iterator makes the second loop empty.
- Early exit.
break,returnand a thrown error insidefor...ofcall the iterator'sreturn()if it exists. Use it to close files or release resources. - Plain objects are not iterable. Use
Object.keys(),Object.values()orObject.entries()to get something you can loop over. - Strings iterate by code point, not by UTF-16 code unit, so
[..."๐"].lengthis 1. - Do not confuse it with
Symbol.asyncIterator, which is used byfor await...ofand returns an async iterator. - Spread and destructuring consume the iterator. Destructuring
const [a, b] = iterablereads two values, then callsreturn().
Browser support
Symbol.iterator and the iteration protocol work in every current browser and in Node.js.