Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Destructure function parameters in JavaScript

23 Destructuring in a parameter list

fair

Replace a long positional signature with a single options object destructured in the parameter list, with defaults. Make it callable with no argument at all, then show what breaks if you leave off the = {}.

Stuck? Three hints, smallest first
  1. 1. The pattern goes where the parameter name would: ({ a, b = 1 }) => ....
  2. 2. To allow a call with no argument, give the whole parameter a default: ({ a } = {}) => ....
  3. 3. fn.length counts parameters before the first default, and a destructured parameter counts as one.

The answer

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

const receipt = ({ branch = 'Ikeja', totalNgn = 0, currency = 'NGN' } = {}) =>
  `${branch}: ${currency} ${totalNgn}`;

const noWholeDefault = ({ branch }) => branch;
const calledBare = attempt(() => noWholeDefault());

const distance = ([x1, y1], [x2, y2]) => Math.abs(x1 - x2) + Math.abs(y1 - y2);
const rentOf = ({ rentNgn: rent }) => rent;
const label = ({ code }, ...tags) => code + ':' + tags.length;

console.log('no argument    :', receipt());
console.log('keys, any order:', receipt({ totalNgn: 8200, branch: 'Yaba' }));
console.log('partial        :', receipt({ totalNgn: 500 }));
console.log('no = {}        :', calledBare);
console.log('array pattern  :', distance([0, 0], [3, 4]));
console.log('arity          :', receipt.length, noWholeDefault.length, distance.length, label.length);

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('with a default on the whole parameter it can be called bare', receipt(), 'Ikeja: NGN 0');
test('named options arrive in any order', receipt({ totalNgn: 8200, branch: 'Yaba' }), 'Yaba: NGN 8200');
test('a partial object keeps the remaining defaults', receipt({ totalNgn: 500 }), 'Ikeja: NGN 500');
test('without that default an omitted argument throws', calledBare, 'TypeError');
test('array patterns work in a parameter list too', distance([0, 0], [3, 4]), 7);
test('so does renaming', rentOf({ rentNgn: 12000 }), 12000);
test('a destructured parameter counts as one towards length', noWholeDefault.length, 1);
test('and a default on it drops the count to zero', receipt.length, 0);
test('a rest parameter is never counted', label.length, 1);

This is the pattern that killed the positional boolean. render(data, true, false, true) is unreadable at the call site and unextendable in the signature; render(data, { animate: true, cache: false }) reads itself, and every option gets a default in one place where a reader will look for it.

The = {} is not optional decoration. Without it, a pattern parameter is destructuring undefined the moment somebody calls the function with no arguments, which throws. Write it every time the options object is genuinely optional.

Newsletter

New writing, when it lands.

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