iterator[Symbol.iterator]() is the method that makes an iterator iterable. On Iterator.prototype it simply returns the same iterator (this), so features that ask for an iterator can reuse the object you already have.
That is why you can write for (const value of someIterator), spread with [...someIterator], or pass an iterator to Array.from(). JavaScript calls [Symbol.iterator]() for you; you rarely need to call it by hand.
Remember
iterator[Symbol.iterator]()
returns the same iterator (this)
so iterators are also iterable
used by: for...of, [...it], Array.from(it)
call yourself only when learning
day to day: just use for...of
Syntax
You normally use it through for...of or spread. You can also call it with square brackets to see that it returns itself.
JavaScript
const it = [10, 20, 30].values();
console.log(it[Symbol.iterator]() === it); // true
for (const n of it) {
console.log(n);
}
Call
What it does
for (const value of iterator)
Loop over values. The loop calls [Symbol.iterator]() for you.
Helper is still an iterator.map() returns another iterator that is iterable.
Spread works.[...doubled] asks for [Symbol.iterator]() and reads every value.
Array.from works too. A fresh mapped iterator becomes [8, 10].
Compatibility
Browser & Runtime Support
Iterator.prototype[Symbol.iterator]() has been part of iterators since ES2015. Every current browser and Node.js has it.
✓ ES2015 · Widely supported
iterator[Symbol.iterator]()
Supported in Chrome 38+, Edge 12+, Firefox 36+, Safari 9+, Opera 25+ and Node.js 4+. Internet Explorer never got it.
ES2015Standard since
Google Chrome38+ · Desktop & Mobile
Full support
Microsoft Edge12+ · Chromium based
Full support
Mozilla Firefox36+ · Desktop & Mobile
Full support
Apple Safari9+ · macOS & iOS
Full support
Opera25+ · Chromium based
Full support
Samsung Internet3+ · Android
Supported
Android WebView38+ · Chromium based
Supported
Node.js4+ · Server runtime
Supported
DenoRecent versions · JavaScript runtime
Supported
BunRecent versions · JavaScript runtime
Supported
Internet ExplorerNo native support
Not supported
iterator[Symbol.iterator]()Excellent
Bottom line: Safe to use everywhere modern JavaScript runs. It is what makes for...of, spread and destructuring work on iterators.
Frequently Asked Questions
It returns the same iterator object. That makes iterators iterable, so for...of, spread, and Array.from can read their values.
Many language features ask for an iterable first, then call next() on the iterator they get back. Returning this lets an existing iterator play both roles.
Use square brackets with the symbol: const same = iterator[Symbol.iterator](). Most of the time for...of is clearer.
Same idea, different return value. A Set creates a fresh values iterator. An Iterator returns itself so you keep walking the same position.
Yes. Helpers are iterators, and they inherit [Symbol.iterator](), so for...of and spread work on them.