Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Rest vs spread operator in JavaScript

68 Rest and spread, in a call and in a literal

easy

Write a variadic total with a rest parameter, then use spread to push a whole array into a call, to merge two objects, and to turn a Set and a string into arrays. Show what Math.max does with an empty spread, and what object spread copies that JSON then throws away.

Stuck? Three hints, smallest first
  1. 1. Rest gathers, spread scatters. Same three dots, opposite directions, told apart by where they sit.
  2. 2. Math.max() with no arguments is -Infinity, so Math.max(...[]) is too.
  3. 3. Object spread copies own enumerable properties, symbol keys included; array spread needs a real iterable, so [...null] throws while { ...null } is fine.

The answer

const total = (...amounts) => amounts.reduce((sum, n) => sum + n, 0);
const takeThrough = (label, ...rest) => `${label}:${rest.length}`;

const prices = [45000, 12000, 3000];
const sumOfPrices = total(...prices);
const withExtra = total(...prices, 500);
const forwarded = takeThrough('cart', ...prices);
const shifted = takeThrough(...prices);

const biggest = Math.max(...prices);
const ofNothing = Math.max(...[]);
const emptyIsInfinity = ofNothing === -Infinity;

const base = { market: 'Ikeja', currency: 'NGN', open: true };
const patch = { open: false, note: 'renovating' };
const merged = { ...base, ...patch };
const guarded = { ...patch, ...base };

const tag = Symbol('internal');
const spreadKeepsSymbols = { ...{ [tag]: 'yes', shown: 1 } };
const symbolSurvived = spreadKeepsSymbols[tag];
const jsonDropsIt = JSON.stringify(spreadKeepsSymbols);

const seen = new Set(['garri', 'rice', 'garri']);
const fromSet = [...seen];
const fromString = [...'NGN'];
const spreadNullObject = { ...null };
let spreadNullArray;
try {
  spreadNullArray = [...null];
} catch (error) {
  spreadNullArray = error.constructor.name;
}

console.log('total  :', sumOfPrices, withExtra, forwarded, shifted);
console.log('max    :', biggest, '| of nothing:', ofNothing);
console.log('merged :', merged, '| other order:', guarded.open);
console.log('spread :', fromSet, fromString, spreadNullObject, spreadNullArray);

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('a rest parameter gathers however many arguments arrive', [sumOfPrices, withExtra], [60000, 60500]);
test('the named parameter takes the first argument, rest takes whatever is left', [forwarded, shifted], ['cart:3', '45000:2']);
test('spread scatters an array into a call that never asked for one', biggest, 45000);
test('an empty spread leaves Math.max with no arguments at all', emptyIsInfinity, true);
test('in a merge the later spread wins, so order is the whole decision', [merged.open, merged.note, guarded.open], [false, 'renovating', true]);
test('object spread copies symbol keys; JSON.stringify cannot see them', [symbolSurvived, jsonDropsIt], ['yes', '{"shown":1}']);
test('spread reads any iterable, and a Set has already deduplicated', [fromSet, fromString], [['garri', 'rice'], ['N', 'G', 'N']]);
test('object spread shrugs at null; array spread demands an iterable', [spreadNullObject, spreadNullArray], [{}, 'TypeError']);

Rest and spread are the same token doing opposite jobs. In a parameter list or on the left of an assignment it gathers; in a call or a literal it scatters. Rest gives you a real array, which arguments never was, so map and reduce work on it directly.

Math.max(...list) is the classic one-liner and the classic bug: an empty list is not an error, it is -Infinity, and that number goes on to poison whatever arithmetic it lands in. Guard the length, or use reduce with a real starting value.

Object spread and JSON disagree about what a copy is. Spread takes own enumerable properties including symbol keys, but it does not run setters on the target, does not copy the prototype, and does not descend: nested objects are shared by reference. JSON.stringify then quietly drops symbols, functions and undefined, which is why a round trip through JSON is a different operation from a spread, not a deeper version of it.

Newsletter

New writing, when it lands.

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