Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Swap variables with array destructuring in JavaScript

17 Swapping without a temporary

fair

Swap two variables in one line, rotate three, and swap two slots of an array in place. Then assign into existing names with an object pattern, and find out what the two syntax traps around that are.

Stuck? Three hints, smallest first
  1. 1. [a, b] = [b, a]. The right-hand array is built first, so nothing is lost.
  2. 2. A pattern target need not be a plain name: [xs[0], xs[2]] = [xs[2], xs[0]] is legal.
  3. 3. A statement starting with { is read as a block, and a statement starting with [ can be swallowed by the line above it if that line has no semicolon.

The answer

const parses = (src) => {
  try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; }
};
const runStrict = (src) => {
  try { return new Function('"use strict";\n' + src)(); } catch (e) { return e.constructor.name; }
};

let a = 1, b = 2;
[a, b] = [b, a];

let x = 'A', y = 'B', z = 'C';
[x, y, z] = [z, x, y];                       // rotate right, one statement

const stalls = ['A1', 'A2', 'A3'];
[stalls[0], stalls[2]] = [stalls[2], stalls[0]];

let owner, rentNgn;
({ owner, rentNgn } = { owner: 'Ngozi', rentNgn: 12000, extra: 'ignored' });

let m, n;
[m, n] = 'xy';                               // any iterable on the right

const asBlock = parses('let o; { o } = { o: 1 };');
const noSemicolon = runStrict('let p = 1, q = 2;\nconst total = 5\n[p, q] = [q, p]\nreturn [p, q];');
const withSemicolon = runStrict('let p = 1, q = 2;\nconst total = 5;\n[p, q] = [q, p];\nreturn [p, q];');

console.log('swap        :', [a, b]);
console.log('rotate      :', [x, y, z]);
console.log('in place    :', stalls);
console.log('into names  :', owner, rentNgn);
console.log('unparenthesised object pattern:', asBlock);
console.log('line above missing a semicolon:', noSemicolon, '<- ran, then failed');
console.log('same code with the semicolon  :', withSemicolon);

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('one statement swaps two names', [a, b], [2, 1]);
test('and three rotate just as easily', [x, y, z], ['C', 'A', 'B']);
test('a target may be an array slot rather than a name', stalls, ['A3', 'A2', 'A1']);
test('an object pattern in parentheses assigns to existing names', [owner, rentNgn], ['Ngozi', 12000]);
test('keys the pattern did not name are simply ignored', typeof extra, 'undefined');
test('without the parentheses the braces are read as a block', asBlock, 'SyntaxError');
test('the right-hand side may be any iterable', [m, n], ['x', 'y']);
test('a previous line with no semicolon swallows the pattern', noSemicolon, 'TypeError');
test('with the semicolon the swap runs', withSemicolon, [2, 1]);

The swap works because the right-hand side is evaluated completely before any target is written, so [a, b] = [b, a] needs no temporary. Same for the three-way rotate, and same when the targets are array slots.

Both traps are about how a statement starts. { owner } = obj begins with a brace, so the parser sees a block and refuses; the parentheses force it to read an expression. The second is worse, because it is not a syntax error: const total = 5 with no semicolon runs straight into the next line as 5[p, q] = [q, p], which parses, and then throws at runtime. This is the concrete reason the "semicolons are optional" style asks you to start such lines with one.

Newsletter

New writing, when it lands.

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