Hello! In our previous lessons, we've explored how well-known symbols allow us to hook into JavaScript's internal algorithms. We used Symbol.toPrimitive to control how objects convert to primitive values and Symbol.toStringTag to customize their type identification string.
Today, we'll address a more subtle but powerful aspect of object-oriented programming in JavaScript: controlling what kind of object is created by methods on a subclass. When you extend a built-in class like Array and then call a method like .map() or .slice() on your subclass instance, what should the method return? An instance of your subclass, or an instance of the base Array?
This lesson will teach you how to manage this behavior precisely. Your learning outcome is to: Control derived object construction in subclassing using Symbol.species.
We will cover:
- The default behavior of methods that create new instances on subclassed built-in objects.
- The problem this default behavior can cause in certain designs.
- How to use the static getter
[Symbol.species]to specify which constructor should be used to create these new "derived" objects.
1. The Subclassing Conundrum: What's in a slice?
When you extend a built-in class like Array, your subclass inherits all of its powerful methods, such as map, filter, and slice. By default, when these methods create and return a new array, they create an instance of your subclass, not the base Array.
This happens because these methods internally look at the current instance's constructor to determine what kind of new object to create. Let's see this in action with a simple custom array class.
class LoggableArray extends Array {
log(message) {
console.log(`[LoggableArray]: ${message}`);
}
}
const mainArray = new LoggableArray('a', 'b', 'c');
mainArray.log('Initial array created.');
const slicedArray = mainArray.slice(1, 3); // -> ['b', 'c']
console.log(slicedArray instanceof LoggableArray); // true
console.log(slicedArray instanceof Array); // true
// Since slicedArray is a LoggableArray, it has the log method.
slicedArray.log('Sliced array reporting in!');
// Output: [LoggableArray]: Sliced array reporting in!
In many cases, this is exactly the behavior you want. However, it can lead to unexpected results or inefficiencies. Consider a more complex subclass, like a PriorityQueue that extends Array but overrides push to maintain a sorted order. If you .slice() a piece of that queue, should the resulting fragment also be a PriorityQueue that re-sorts itself upon every push? Maybe not. You might just want a plain, standard array.
This is the problem Symbol.species was introduced to solve. It provides an "off-ramp," allowing a class to specify which constructor its methods should use to mint new instances.
2. Introducing Symbol.species
Symbol.species is a well-known symbol that refers to a function-valued property used by constructors to create derived objects. In simpler terms, it's a static getter you define on your class that returns the constructor function you want methods like .map() or .slice() to use.
Let's modify our LoggableArray to return a plain Array from its methods.
class LoggableArray extends Array {
log(message) {
console.log(`[LoggableArray]: ${message}`);
}
// This static getter tells methods like slice() and map()
// to use the Array constructor for new instances.
static get [Symbol.species]() {
return Array;
}
}
const mainArray = new LoggableArray('a', 'b', 'c');
const slicedArray = mainArray.slice(1, 3);
console.log(slicedArray instanceof LoggableArray); // false
console.log(slicedArray instanceof Array); // true
// This will now cause an error, because slicedArray is a plain Array.
// slicedArray.log('This will fail.'); // TypeError: slicedArray.log is not a function
By adding the static [Symbol.species] getter, we've instructed any method on LoggableArray that creates a new instance to use the original Array constructor instead of LoggableArray. The built-in methods of Array are specifically designed to check for this symbol. The logic is roughly:
- Is
this.constructor[Symbol.species]defined? - If yes, use it as the constructor for the new instance.
- If no, fall back to using
this.constructor.
The following reading from a Stack Overflow discussion provides an excellent, practical example using a PriorityQueue to solidify this concept.
What's the difference between `Object.prototype.constructor` and `Symbol.species`? - Stack Overflow
This Stack Overflow answer clearly explains the difference between .constructor and Symbol.species and provides a fantastic PriorityQueue example that demonstrates the default behavior and how to override it.
Please read the accepted answer by user 'trincot'. Focus on the two code snippets demonstrating the PriorityQueue class: the first shows the default behavior where .slice() returns another PriorityQueue, and the second shows how adding Symbol.species changes the result to a plain Array.
As the resource highlights, Symbol.species is distinct from the constructor property.
instance.constructorpoints to the function that created the instance.Class[Symbol.species]is a static property on the class that tells its methods how to create derived instances.
3. Usage with Other Built-in Classes
The Symbol.species pattern is not limited to Array. It's a general mechanism that applies to other built-in classes that have methods for creating new instances, such as Map, Set, Promise, and RegExp.
The article below shows how this applies to both Array and Map.
Master Symbol.species: Custom JS Objects
This article, 'Master Symbol.species for Custom Object Creation in JavaScript', provides further code examples and context. We'll use it to see how the pattern applies to a Map subclass.
Please read the sections 'Example 1: Custom Array Subclass' and 'Example 2: Custom Map Subclass'. The array example reinforces what we've learned, and the map example demonstrates the same principle on a different built-in object.
Another good example is with RegExp. Some regular expression methods can return new RegExp objects. Subclassing RegExp might involve adding custom logging or analysis methods, but you might want the derived regular expressions to be standard, performant RegExp objects.

Test your understanding!
Drawing from your interest in game development, let's create a special Inventory class that extends Array. This class has a special method, checkWeight(), which is computationally expensive.
When a player gives a few items to an NPC, you might use .slice() to create a new array representing those items. For efficiency, you don't want this new, temporary array of items to be a full-fledged Inventory object with the expensive checkWeight method.
Your task: Complete the Inventory class below so that methods like .slice() and .map() return a standard Array, not another Inventory instance.
class Inventory extends Array {
constructor(...items) {
super(...items);
}
checkWeight() {
// A simulated expensive operation
const weight = this.reduce((acc, item) => acc + (item.weight || 0), 0);
console.log(`Total weight is: ${weight}`);
return weight;
}
// YOUR IMPLEMENTATION HERE
}
const playerInventory = new Inventory(
{ name: 'Sword', weight: 10 },
{ name: 'Shield', weight: 15 },
{ name: 'Potion', weight: 1 }
);
const itemsToGive = playerInventory.slice(1, 3); // A Shield and a Potion
// This should be FALSE
console.log('Is `itemsToGive` an Inventory?', itemsToGive instanceof Inventory);
// This should throw an error because `itemsToGive` should be a plain array
try {
itemsToGive.checkWeight();
} catch (e) {
console.log('Success:', e.message);
}
Show answer
You need to add a static getter for Symbol.species that returns the Array constructor.
class Inventory extends Array {
constructor(...items) {
super(...items);
}
checkWeight() {
// A simulated expensive operation
const weight = this.reduce((acc, item) => acc + (item.weight || 0), 0);
console.log(`Total weight is: ${weight}`);
return weight;
}
// Solution: Return the base Array constructor for derived objects.
static get [Symbol.species]() {
return Array;
}
}
const playerInventory = new Inventory(
{ name: 'Sword', weight: 10 },
{ name: 'Shield', weight: 15 },
{ name: 'Potion', weight: 1 }
);
const itemsToGive = playerInventory.slice(1, 3);
console.log('Is `itemsToGive` an Inventory?', itemsToGive instanceof Inventory); // false
try {
itemsToGive.checkWeight();
} catch (e) {
console.log('Success:', e.message); // Success: itemsToGive.checkWeight is not a function
}
Conclusion
In this lesson, we tackled the nuances of instance creation within class hierarchies. You learned how to gain explicit control over the type of objects returned by methods on your custom subclasses.
Key Takeaways:
- By default, methods on subclassed built-ins (like
Array.prototype.slice) return new instances of the subclass, not the base class. Symbol.speciesis astaticgetter you can add to your class to override this behavior.- The getter should return a constructor function (e.g.,
Array,Map,RegExp). Built-in methods will then use this constructor to create derived instances. - This is a powerful tool for designing class hierarchies, allowing you to prevent derived objects from unnecessarily inheriting complex behaviors or properties.
Next Up
We have now seen how symbols can customize primitive conversion (toPrimitive), type tagging (toStringTag), and derived instance creation (species). The next logical step is to customize how JavaScript checks an object's type. In the next lesson, we will explore Symbol.hasInstance, which allows you to define the logic for the instanceof operator for your classes, giving you complete control over what it means for an object to be an "instance" of your class.