Well-Known Symbols in JavaScript: Symbol.toPrimitive, toStringTag, hasInstance, species and More
Customize how built-in operations treat your objects with well-known symbols: Symbol.iterator and asyncIterator, toPrimitive hints, toStringTag for type labels, hasInstance for instanceof, species for array subclasses, isConcatSpreadable, the regex symbols match, replace and split, and unscopables.
kvi5hnuCode Sprout team member6 min readOn this page
Article 19 introduced symbols and mentioned that a few of them are well-known: predefined symbols stored as properties of Symbol, such as Symbol.iterator. They're the language's extension points. Whenever an operation like for...of, instanceof or string conversion works on an object, the engine looks for a method under a specific well-known symbol and, if it finds one, lets your code decide what happens. This article tours them all, from the ones you'll use weekly to the ones you mostly need to recognize.

Because they're symbols, these hooks can never clash with ordinary string-named properties, which is why the language could add them in ES2015 without breaking existing code.
Symbol.iterator and Symbol.asyncIterator
You've already used these: they make an object iterable for for...of, spread and destructuring (article 90), and async-iterable for for await...of (article 99). They're by far the most common well-known symbols in everyday code.
class Range {
constructor(from, to) {
this.from = from;
this.to = to;
}
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n++) yield n;
}
}
console.log([...new Range(1, 4)], Math.max(...new Range(3, 7)));
[ 1, 2, 3, 4 ] 7
Symbol.toPrimitive
When an object is used where a primitive is needed, JavaScript calls obj[Symbol.toPrimitive](hint) if it exists, instead of the valueOf/toString fallback described in article 24. The hint tells you what the context wants:
| Hint | Contexts |
|---|---|
"number" | unary +, *, -, <, >, Number(obj), Math functions |
"string" | template literals, String(obj), property keys |
"default" | binary + and == (which could mean either) |
class Money {
constructor(amount, currency) {
this.amount = amount;
this.currency = currency;
}
[Symbol.toPrimitive](hint) {
return hint === "number" ? this.amount : `${this.amount.toFixed(2)} ${this.currency}`;
}
}
const price = new Money(9.5, "EUR");
console.log(+price, price * 2, price > 5);
console.log(`${price}`);
console.log(price + 1);
9.5 19 true
9.50 EUR
9.50 EUR1
The last line is the usual trap: binary + uses the "default" hint, and this method returns a string for it, so + 1 concatenates. The method must return a primitive, or the conversion throws a TypeError. Date objects use this symbol to make date + "" produce a string while date - other produces a number.
Symbol.toStringTag
Object.prototype.toString produces strings like "[object Array]", and many libraries use it for type checks because it works across realms (iframes, worker contexts). The part after object comes from Symbol.toStringTag:
class Temperature {
get [Symbol.toStringTag]() {
return "Temperature";
}
}
const typeOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
console.log(typeOf(new Temperature()), typeOf([]), typeOf(null), typeOf(new Map()), typeOf(Promise.resolve()));
console.log(String(new Temperature()));
Temperature Array Null Map Promise
[object Temperature]
Built-ins like Map, Promise, Symbol and typed arrays define their own toStringTag. Node's console.log and util.inspect also show it when printing objects.
Symbol.hasInstance
x instanceof C actually calls C[Symbol.hasInstance](x). Every function inherits a default implementation from Function.prototype that walks the prototype chain (article 70). Defining your own static method changes what instanceof means for that object:
const Even = {
[Symbol.hasInstance](n) {
return Number.isInteger(n) && n % 2 === 0;
},
};
console.log(4 instanceof Even, 7 instanceof Even);
class Duck {
static [Symbol.hasInstance](obj) {
return typeof obj?.quack === "function"; // duck typing
}
}
console.log({ quack() {} } instanceof Duck, {} instanceof Duck);
true false
true false
It's a neat demonstration, but use it sparingly: readers expect instanceof to mean "inherits from", and a type guard function such as isDuck(obj) is clearer.
Symbol.species
When you call map, filter or slice on an instance of an Array subclass, the result is created through this.constructor[Symbol.species]. By default that's the subclass itself, so results keep your class. Override it to return plain arrays:
class Stack extends Array {
peek() {
return this.at(-1);
}
}
class PlainResults extends Array {
static get [Symbol.species]() {
return Array;
}
}
const stack = Stack.from([1, 2, 3]);
console.log(stack.map((x) => x * 2) instanceof Stack, stack.filter(Boolean).peek());
const results = PlainResults.from([1, 2]);
console.log(results.map((x) => x).constructor.name);
true 3
Array
Promise, Map, Set, RegExp, ArrayBuffer and typed arrays also consult Symbol.species when they create derived objects (for example, promise.then uses it to construct the returned promise). Species makes engines slower and has caused security bugs, so TC39 has discussed limiting it, and newer built-in methods deliberately ignore it: the ES2023 copying methods toSorted, toReversed and with always return plain arrays. Avoid relying on it in new code.
Symbol.isConcatSpreadable
Array.prototype.concat flattens array arguments one level but adds other objects as single elements. This symbol overrides that choice in either direction:
const arrayLike = { length: 2, 0: "a", 1: "b", [Symbol.isConcatSpreadable]: true };
console.log([1].concat(arrayLike));
const keepWhole = [3, 4];
keepWhole[Symbol.isConcatSpreadable] = false;
console.log([1, 2].concat(keepWhole).length);
[ 1, 'a', 'b' ]
3
The regular expression symbols
The string methods match, matchAll, replace, replaceAll, search and split accept a pattern argument. They don't hard-code RegExp: they look up Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search or Symbol.split on it and delegate to that method. RegExp.prototype implements all of them, and you can implement them too:
const commaList = {
[Symbol.split](text) {
return text.split(",").map((part) => part.trim()).filter(Boolean);
},
};
const vowels = {
[Symbol.replace](text, replacement) {
return text.replace(/[aeiou]/g, replacement);
},
};
console.log("red , green,, blue ".split(commaList));
console.log("banana".replace(vowels, "*"));
[ 'red', 'green', 'blue' ]
b*n*n*
Symbol.match also serves as an "is this a regex?" flag. startsWith, endsWith and includes throw a TypeError if given a regex, and setting re[Symbol.match] = false tells them to treat it as a plain object (converted to its string form).
Symbol.unscopables
This one exists only for backward compatibility with the deprecated with statement (forbidden in strict mode). Array.prototype[Symbol.unscopables] lists newer method names, like at, flat, includes and toSorted, that with (array) must not expose as variables. Without it, adding these methods would have broken old sloppy-mode code that had variables with the same names. You'll never need to define it yourself, but it explains an odd object you may see when inspecting Array.prototype.
Symbol.dispose and Symbol.asyncDispose
The newest well-known symbols power using and await using (article 100). An object with a [Symbol.dispose]() method can be declared with using, and it's cleaned up automatically at the end of the block.
The full list
const names = Object.getOwnPropertyNames(Symbol).filter((key) => typeof Symbol[key] === "symbol");
console.log(names.join(", "));
asyncIterator, hasInstance, isConcatSpreadable, iterator, match, matchAll, replace, search, species, split, toPrimitive, toStringTag, unscopables, dispose, asyncDispose
Common questions
Why are these hooks symbols instead of normal method names?
Symbols are guaranteed unique, so adding a new hook to the language can't collide with existing properties named iterator or species in real-world code. That's what allowed ES2015 (and later editions) to add them safely.
What's the difference between Symbol.toPrimitive and valueOf/toString?
Symbol.toPrimitive takes priority and receives a hint, so one method handles every conversion context. Without it, the engine tries valueOf then toString (or the reverse for string contexts), as article 24 describes.
Is Object.prototype.toString.call reliable for type checking?
For built-ins it's reliable across realms, which is why libraries use it. But any object can fake the result with Symbol.toStringTag, so it's not a security check. For arrays specifically, use Array.isArray.
Should I use Symbol.species in my own classes?
Rarely. It mostly matters for subclasses of Array and Promise, newer methods ignore it, and overriding it can surprise users. Prefer composition over subclassing built-ins (article 73).
Summary
- Well-known symbols are properties of
Symbolthat built-in operations look up on your objects. Symbol.iterator/asyncIteratorenable iteration;Symbol.dispose/asyncDisposeenableusing.Symbol.toPrimitive(hint)controls conversions; the"default"hint for binary+is the classic surprise.Symbol.toStringTaglabels objects forObject.prototype.toString;Symbol.hasInstancecustomizesinstanceof.Symbol.specieschooses the class of derived arrays and promises;Symbol.isConcatSpreadablecontrolsconcat.Symbol.match,matchAll,replace,searchandsplitlet any object act as a pattern;Symbol.unscopablesexists forwithcompatibility.
Practice Questions
What does this print?
const t = {
[Symbol.toPrimitive](hint) {
return hint === "number" ? 42 : "t";
},
};
console.log(t * 1, `${t}`, t + 1);
Answer
42 t t1. Multiplication uses the "number" hint and the template literal uses "string". Binary + uses "default", which this method treats like a string, so it concatenates.
Make Object.prototype.toString.call(new Vector()) return "[object Vector]".
Answer
class Vector {
get [Symbol.toStringTag]() {
return "Vector";
}
}
What does filtered.constructor.name print, and why?
class Tags extends Array {}
const filtered = Tags.from(["a", "b"]).filter((t) => t !== "a");
Answer
Tags. filter creates its result through this.constructor[Symbol.species], which defaults to the subclass. Defining static get [Symbol.species]() { return Array; } would make it a plain Array.
Why does "abc".startsWith(/a/) throw, and what makes it stop throwing?
Answer
startsWith refuses regex arguments, and it detects them through Symbol.match, throwing a TypeError. Setting re[Symbol.match] = false marks the object as "not a regex". The method then converts it to the string "/a/" and checks for that text.
Next: The JavaScript Reflect API: Reflect.get, set, has, ownKeys, apply and construct

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.