Skip to content

Well-Known Symbols

Well-known symbols are built-in Symbol values that let you customize how objects interact with JavaScript’s internal operations.

Makes objects iterable (used by for...of, spread, destructuring):

class Range {
constructor(start, end) { this.start = start; this.end = end; }
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current <= end
? { value: current++, done: false }
: { done: true };
}
};
}
}
for (const n of new Range(1, 5)) console.log(n); // 1 2 3 4 5

Controls how objects are converted to primitive values:

const temperature = {
value: 100,
unit: 'C',
[Symbol.toPrimitive](hint) {
if (hint === 'number') return this.value;
if (hint === 'string') return `${this.value}°${this.unit}`;
return this.value;
}
};
console.log(+temperature); // 100 (number hint)
console.log(`${temperature}`); // '100°C' (string hint)
console.log(temperature + ''); // '100°C' (default hint → string)

Customizes Object.prototype.toString output:

class MyCollection {
get [Symbol.toStringTag]() {
return 'MyCollection';
}
}
const mc = new MyCollection();
console.log(Object.prototype.toString.call(mc));
// '[object MyCollection]'

Customizes instanceof behavior:

class Range {
static [Symbol.hasInstance](instance) {
return instance >= 0 && instance <= 100;
}
}
console.log(50 instanceof Range); // true
console.log(200 instanceof Range); // false
SymbolPurpose
Symbol.iteratorMake objects iterable
Symbol.asyncIteratorMake objects async iterable
Symbol.toPrimitiveCustom type conversion
Symbol.toStringTagCustom Object.prototype.toString
Symbol.hasInstanceCustom instanceof
Symbol.speciesConstructor for derived objects
Symbol.matchCustom RegExp matching
Symbol.replaceCustom string replacement
Symbol.searchCustom string search
Symbol.splitCustom string splitting
Symbol.unscopablesExclude keys from with binding
  • Well-known symbols customize internal JavaScript behavior
  • Most common: Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag
  • They’re part of the ECMAScript specification
  • Enable metaprogramming patterns