Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Symbol.species and Array subclasses in JavaScript

70 Symbol.species decides what map gives back

hard

Subclass Array and check what filter returns. Then set Symbol.species to Array and check again. Find out what the species constructor is called with, and what that does to a subclass whose own first argument is not a length.

Stuck? Three hints, smallest first
  1. 1. Array methods that build a new array ask the instance for a constructor rather than using Array.
  2. 2. static get [Symbol.species]() { return Array; } is the whole opt-out.
  3. 3. The species constructor is invoked with the new length. A subclass expecting a name receives a number.

The answer

class Fares extends Array {
  totalNaira() { return this.reduce((sum, fare) => sum + fare, 0); }
}
const fares = new Fares();
fares.push(300, 500, 250);

const filtered = fares.filter((fare) => fare >= 300);
const keepsSubclass = [filtered instanceof Fares, Array.isArray(filtered), filtered.totalNaira()];

class PlainResults extends Array {
  static get [Symbol.species]() { return Array; }
  totalNaira() { return this.reduce((sum, fare) => sum + fare, 0); }
}
const plain = new PlainResults();
plain.push(300, 500, 250);
const mapped = plain.map((fare) => fare * 2);
const nowPlain = [mapped instanceof PlainResults, Array.isArray(mapped), typeof mapped.totalNaira];
const originalKeepsIt = plain.totalNaira();

// What the species constructor is called with: the new length.
class Ledger extends Array {
  constructor(till) { super(); this.till = till; }
}
const ledger = new Ledger('Balogun 3');
ledger.push(300, 500);
const mappedCopy = ledger.map((fare) => fare);
const filteredCopy = ledger.filter(() => true);
const tillBecameALength = [mappedCopy.till, filteredCopy.till, mappedCopy.length, mappedCopy instanceof Ledger];

class FixedLedger extends Array {
  static get [Symbol.species]() { return Array; }
  constructor(till) { super(); this.till = till; }
}
const fixed = new FixedLedger('Balogun 3');
fixed.push(300, 500);
const fixedCopy = fixed.filter(() => true);
const noStrayTill = [fixedCopy.till === undefined, fixedCopy.length, fixed.till];

const otherMethods = [
  plain.slice(0, 2) instanceof PlainResults,
  plain.concat([100]) instanceof PlainResults,
  fares.slice(0, 2) instanceof Fares,
];

class Receipts extends Promise {}
const chained = Receipts.resolve('LAG-0070').then((ref) => ref);
const promiseSpecies = [chained instanceof Receipts, chained instanceof Promise];

console.log('filter keeps the subclass:', keepsSubclass);
console.log('species Array           :', nowPlain);
console.log('the till became         :', tillBecameALength, '<- map passes the length, filter passes 0');

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('by default filter returns the subclass, so its methods survive', keepsSubclass, [true, true, 800]);
test('species set to Array makes map return a plain array', nowPlain, [false, true, 'undefined']);
test('while the original still has its own method', originalKeepsIt, 1050);
test('the species constructor is called with a length, so the till became a number', tillBecameALength, [2, 0, 2, true]);
test('opting out means the subclass constructor is not called at all', noStrayTill, [true, 2, 'Balogun 3']);
test('slice and concat obey species the same way map and filter do', otherMethods, [false, false, true]);
test('Promise uses the same mechanism, so then returns the subclass', promiseSpecies, [true, true]);
test('and Array.isArray is true either way: species changes the class, not the kind', [Array.isArray(mapped), Array.isArray(filtered)], [true, true]);

map, filter, slice, splice, concat, flat and flatMap do not construct an Array. They call ArraySpeciesCreate, which asks the instance's constructor for Symbol.species and uses that. The default is the subclass, which is usually what you want — fares.filter(...) still has totalNaira.

The fourth assertion is why the opt-out exists. ArraySpeciesCreate invokes the constructor with a length, so Ledger, whose first parameter is a till name, was handed a number and stored it as this.till. Which number depends on the method: map passes the source length, so the till became 2, and filter passes 0 because it does not know yet how many elements will survive. No error, no warning either way: the copy is a Ledger with a numeric till. Any subclass of Array whose constructor takes something other than a length has this bug, and the only complete fixes are to declare Symbol.species as Array or to stop extending Array.

The general lesson is worth more than the mechanism. Extending a built-in means every method on it becomes a constructor call you did not write, and the built-in decides the arguments. Composition — a class with an array field — has no such surprises, which is why most codebases stopped subclassing Array.

Promise, RegExp, typed arrays and ArrayBuffer all use species too, so then on a promise subclass builds another instance of the subclass. Same rule, same trap: whatever your constructor requires, the built-in will call it with the arguments the specification chose.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.