freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #26 of 61

iterators · symbol.iterator

LambdaVSThe Mutator
Lambda saysIterators implement the protocol that makes for...of and spread work.

An object is iterable if it has a [Symbol.iterator]() method returning an iterator (with a next() that yields {value, done}). Arrays, strings, Maps, and Sets implement it. You can make your own objects iterable — then for...of and spread work on them automatically.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleMake a small object iterable so for...of can loop its items.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const range={from:1,to:3,[Symbol.iterator](){let i=this.from,to=this.to;return{next:()=>i<=to?{value:i++,done:false}:{value:undefined,done:true}};}};
document.getElementById('o').textContent=[...range].join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ Array-Like Vs ArrayGenerators · Function* · Yield ›