Species and built-in result construction
Quick answer
Symbol.species is a constructor-selection hook used by some built-in methods when creating their results. It does not control every copying method.
How it works
An Array subclass can define static get [Symbol.species]() { return Array; }. Methods such as map and slice consult array species; modern copying methods such as toReversed use ordinary arrays instead. A null or undefined species selects the default constructor. An invalid nonconstructor species can throw. The getter can execute arbitrary code; prefer predictable ordinary array results when subclassing is unnecessary.
class Prices extends Array {static get [Symbol.species](){return Array;}} const p=new Prices(2,3); const r=p.map(x=>x*2); console.log(r instanceof Prices,JSON.stringify(r));Expected output in Node.js:
false [4,6]map selects Array for the result.
class List extends Array {} const a=new List(2,3); console.log(a.slice() instanceof List,a.toReversed() instanceof List);Expected output in Node.js:
true falseslice consults species but toReversed creates an ordinary array.
Common mistakes
Do not assume every method preserves the subclass or every copying method consults species. Verify each algorithm.
Practice
Compare map, slice and toReversed on an Array subclass with and without a species override.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Species and built-in result construction — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which Array operation in this lesson consults species?
What does a null species select?
Why avoid unnecessary species overrides?
What is the exact console output in Species and built-in result construction example 1?
class Prices extends Array {static get [Symbol.species](){return Array;}} const p=new Prices(2,3); const r=p.map(x=>x*2); console.log(r instanceof Prices,JSON.stringify(r));What is the exact console output in Species and built-in result construction example 2?
class List extends Array {} const a=new List(2,3); console.log(a.slice() instanceof List,a.toReversed() instanceof List);