JS Built-ins
ArrayArray[Symbol.species]advanced

Array[Symbol.species] β€” subclass filter()

πŸ“– Usage Example
class MyArr extends Array {}
const a = new MyArr(1, 2, 3, 4)
a.filter(x => x > 2) instanceof MyArr  // β†’ true

filter() on a subclass of Array returns an instance of that subclass via Symbol.species.

Array[Symbol.species] and filter()

Just like .map(), the .filter() method also respects Symbol.species. When called on an Array subclass, it returns an instance of the subclass rather than a plain Array.

Challenge: Create TypedArray that extends Array. Implement filterReturnsSubclass that returns true when .filter() on a TypedArray instance produces another TypedArray instance.

filterReturnsSubclass() // β†’ true
πŸ’‘ Hints (2)
  • β€’ `.filter()` uses `Symbol.species` internally to construct its return value.
  • β€’ Extending `Array` is enough β€” no need to override `Symbol.species` for the default behaviour.