Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Array destructuring: skip, rest and defaults in JavaScript

67 Array patterns: swap, skip, rest and a default that costs something

fair

Use array patterns for the four things they are good at: swapping two variables with no temporary, skipping elements you do not want, collecting the tail with a rest element, and defaulting a missing element from a function call. Then count how many times that default function actually ran.

Stuck? Three hints, smallest first
  1. 1. A hole in the pattern skips a position: const [, second] = list.
  2. 2. A default in a pattern is an expression, and expressions in defaults are lazy: it is only evaluated when that position is undefined.
  3. 3. A rest element must come last, and it is always an array, even when there is nothing left to put in it.

The answer

let first = 'Ikeja';
let second = 'Yaba';
[first, second] = [second, first];

const readings = [12, 45, 78, 91, 103];
const [, secondReading, , ...tail] = readings;

let lookups = 0;
const fallbackRate = () => {
  lookups++;
  return 1500;
};
const [cheap = fallbackRate(), dear = fallbackRate()] = [900];

const rows = [['Adaeze', 3], ['Bola', 1]];
const named = rows.map(([who, howMany]) => `${who} x${howMany}`);

const [[a, b], [c]] = [[1, 2], [3, 4]];
const [x, y, z] = 'NG';
const [only, missing] = [7];
const [head, ...nothingLeft] = [7];

const tally = new Map([['garri', 2], ['rice', 5]]);
const asLines = [];
for (const [good, count] of tally) asLines.push(`${good}=${count}`);

console.log('swap    :', first, second);
console.log('skipped :', secondReading, tail);
console.log('lazy    :', cheap, dear, '| fallback ran', lookups, 'time(s)');
console.log('nested  :', a, b, c, '| string:', x, y, z);

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 swap needs no temporary, because the right side is built first', [first, second], ['Yaba', 'Ikeja']);
test('holes skip positions and the rest element takes everything after', [secondReading, tail], [45, [91, 103]]);
test('the default only ran for the position that was missing', [cheap, dear, lookups], [900, 1500, 1]);
test('a pattern in a parameter list unpacks each row', named, ['Adaeze x3', 'Bola x1']);
test('patterns nest, and a string is iterable so it destructures too', [a, b, c, x, y, z === undefined], [1, 2, 3, 'N', 'G', true]);
test('asking for more than there is gives undefined, not an error', [only, missing === undefined], [7, true]);
test('but a rest element is an array even when it is empty', [head, nothingLeft], [7, []]);
test('and a Map entry is a two-element array, so the for...of head can unpack it', asLines, ['garri=2', 'rice=5']);

The swap works because the right-hand side is fully evaluated into a new array before any binding on the left is written. That is also why it needs no temporary and why it generalises: [a, b, c] = [c, a, b] rotates three values in one line.

Watch the semicolon. A line that starts with [ continues the line above it, so let a = 1 followed by [a, b] = [b, a] with no semicolon parses as let a = 1[a, b] and fails in a way that reads like nonsense. This is the one place in ordinary code where leaving a semicolon off genuinely breaks the program.

Two details worth keeping. A missing element gives undefined rather than throwing, so a pattern is a soft read and you check afterwards if it mattered. And defaults are lazy expressions, so the fallback lookup above ran once, not twice — which is what makes const [rate = expensiveLookup()] = row safe to write.

Newsletter

New writing, when it lands.

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