Array[Symbol.species]
The Array[Symbol.species]
accessor property returns the constructor used to construct return values from array methods.
Warning: The existence of
[Symbol.species]
allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.
Syntax
Array[Symbol.species]
Return value
The value of the constructor (this
) on which get [Symbol.species]
was called. The return value is used to construct return values from array methods that create new arrays.
Description
The [Symbol.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:
// Hypothetical underlying implementation for illustration
class Array {
static get [Symbol.species]() {
return this;
}
}
Because of this polymorphic implementation, [Symbol.species]
of derived subclasses would also return the constructor itself by default.
class SubArray extends Array {}
SubArray[Symbol.species] === SubArray; // true
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[Symbol.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); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 }
arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 }
arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 }