Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Spread an array into function arguments in JavaScript

29 Spreading into a call

fair

Pass an array to a function that expects separate arguments, mix a spread with fixed arguments, spread into new, and find the one thing apply could not do. Then check what happens when the array is very large.

Stuck? Three hints, smallest first
  1. 1. f(...xs) is the argument-list form of the same three dots, and replaces f.apply(null, xs).
  2. 2. It may appear anywhere in the argument list, more than once, and alongside ordinary arguments.
  3. 3. Every argument lives on the stack, so an enormous spread can exceed the engine’s limit — a reduce never can.

The answer

const attempt = (fn) => {
  try { return fn(); } catch (e) { return e.constructor.name; }
};

const nums = [3, 41, 7];
const label = (a, b, c) => [a, b, c].join('-');

class Money {
  constructor(major, minor) { this.kobo = major * 100 + minor; }
}

let taken = 0;
function* three() {
  for (const n of [1, 2, 3]) { taken++; yield n; }
}
const fromGenerator = label(...three());

const big = Array.from({ length: 200000 }, (_, i) => i);
const spreadBig = attempt(() => Math.max(...big));
const outcome = typeof spreadBig === 'number' ? 'a number' : spreadBig;
const byReduce = big.reduce((m, x) => (x > m ? x : m), -Infinity);

console.log('spread     :', Math.max(...nums), '| apply:', Math.max.apply(null, nums));
console.log('mixed      :', label(...['x', 'y'], 'z'), label('x', ...['y', 'z']));
console.log('any iterable:', Math.min(...new Set([9, 4, 4])));
console.log('with new   :', new Money(...[120, 50]).kobo);
console.log('generator  :', fromGenerator, 'values taken:', taken);
console.log('200k spread:', outcome, '| the same answer by reduce:', byReduce);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('spread turns an array into an argument list', Math.max(...nums), 41);
test('which is what apply was for', Math.max.apply(null, nums), 41);
test('a spread may be mixed with fixed arguments, at either end', [label(...['x', 'y'], 'z'), label('x', ...['y', 'z'])], ['x-y-z', 'x-y-z']);
test('any iterable can be spread into a call', Math.min(...new Set([9, 4, 4])), 4);
test('spreading nothing is simply a call with no arguments', Math.max(...[]) === -Infinity, true);
test('unlike apply, spread works with new', new Money(...[120, 50]).kobo, 12050);
test('a generator is drained exactly once', [fromGenerator, taken], ['1-2-3', 3]);
test('a huge spread is engine-dependent: a number or a RangeError', ['a number', 'RangeError'].includes(outcome), true);
test('a reduce has no argument limit and gives the same answer', byReduce, 199999);

Math.max(...xs) is the idiom, and it is also the classic outage. Arguments are pushed on the stack, so somewhere above a hundred thousand or so — the exact number varies by engine and by how much stack is left — the call throws a RangeError instead of returning. This assertion accepts either result on purpose, because pinning it to one number would be a claim about an engine rather than about JavaScript. For a list of unknown size, reduce.

The new assertion is the reason spread is not just sugar for apply. apply calls; it cannot construct. Before spread you needed Reflect.construct or a bind trick to hand an array to a constructor.

Newsletter

New writing, when it lands.

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