Symbol.species for Derived Constructors
What you'll learn: How to control which constructor gets used when built-in methods create new instances from derived classes.
The Challenge with Derived Classes
When you extend a built-in class like Array, methods like map() or slice() automatically create new instances. By default, they use your derived constructor. But what if you want them to return plain Array instances instead? That's where Symbol.species comes in.
How Symbol.species Works
Symbol.species is a static accessor property that tells JavaScript which constructor to use when creating derived objects. Think of it as a "birth certificate" — it specifies the parent type for new offspring.
class MyArray extends Array {
static get [Symbol.species]() {
return Array; // Use Array, not MyArray
}
}
const myArr = new MyArray(1, 2, 3);
const mapped = myArr.map(x => x * 2);
console.log(myArr instanceof MyArray); // true
console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
Without Symbol.species, mapped would be an instance of MyArray. By returning Array, we tell map() to create a plain array instead.
When to Use It
This is useful when your derived class adds special behavior or properties that shouldn't carry over to every method result. For example, if your custom array tracks metadata, you might not want that baggage in every filtered or mapped result.
class CustomArray extends Array {
// Keep default behavior - returns CustomArray instances
}
const custom = new CustomArray(1, 2, 3);
const sliced = custom.slice(1);
console.log(sliced instanceof CustomArray); // true (default)
Key Takeaway: Symbol.species lets you specify which constructor built-in methods should use when creating new instances, giving you control over the inheritance chain of derived objects.