The @@species
accessor property returns the default constructor for Array
objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:
class Array {
static get [Symbol.species]() {
return this;
}
}
Because of this polymorphic implementation, @@species
of derived subclasses would also return the constructor itself by default.
class SubArray extends Array {}
SubArray[Symbol.species] === SubArray;
When calling array methods that do not mutate the existing array but return a new array instance (for example, filter()
and map()
), the array's constructor[@@species]
will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays.
class NotAnArray {
constructor(length) {
this.length = length;
}
}
const arr = [0, 1, 2];
arr.constructor = { [Symbol.species]: NotAnArray };
arr.map((i) => i);
arr.filter((i) => i);
arr.concat([1, 2]);