Skip to content

Symbols & Iterators

JavaScript

Learn Symbols, iterables, iterators, and generator functions.

Official Site
01

Overview

Symbols are unique, non-enumerable identifiers. Well-known symbols: Symbol.iterator, Symbol.asyncIterator. Iterables implement [Symbol.iterator]. Generators (function*) yield values lazily. for-of consumes iterables.

bash
const unique=Symbol("id");
const range={from:1,to:3,[Symbol.iterator](){let i=this.from;const t=this.to;return{next(){return i<=t?{value:i++}:{done:true};}};}};
[...range]; // [1,2,3]
function* gen(){yield 1; yield 2; }
02

Best Practices

Use Symbol for private-ish object keys. Implement Symbol.iterator for custom iterables. Use generators for lazy sequences. async generators for async streams. Symbols are not enumerated by for-in/Object.keys.

Ready to try Symbols & Iterators?

Visit the official site for the latest version and full documentation.

Visit Symbols & Iterators