easyJS ES6+#68

Spread and rest operators

Prompt

Write a function mergeAndSum that takes any number of arrays (rest param), flattens them (spread) and returns the sum of all numbers.

Solution

function mergeAndSum(...arrays) {
  const flat = [].concat(...arrays)
  return flat.reduce((sum, n) => sum + n, 0)
}
Mentor's take

Rest and spread are the same ... token doing opposite jobs, and naming the direction is the point: rest collects (variadic arguments into a real array — no more arguments object, which isn't an array and doesn't exist in arrow functions) and spread expands (an iterable into individual elements). Here ...arrays gathers any number of arrays, then [].concat(...arrays) spreads them back out as separate arguments to concat, which flattens exactly one level.

The reduce with an explicit initial value 0 is not decoration: without it, mergeAndSum() on zero arrays would throw TypeError: Reduce of empty array with no initial value. The empty-input case is the edge interviewers wait for, and the initial value handles it for free.

Two limits worth volunteering: spread is shallow — it copies references one level deep, so spreading an array of objects shares the objects — and spreading into a function call materializes every element as an argument, which can overflow the engine's argument limit on very large arrays (arr.flat() or a loop avoids that).

Red flag: saying spread "copies" an array or object without qualifying shallow. [...state] gives a new outer array with the same inner references — mutate a nested object and both copies see it. In React that's the classic "I spread it but the component didn't re-render correctly" bug.

Say it: "Rest collects arguments into a real array and spread expands iterables — both are shallow, one level deep, so spreading never deep-clones nested structures."