0
Challenge · 13Just Enough JavaScript

Destructuring, spread and swapping

JavaScriptused in ~80% of apps

Three small pieces of shorthand that appear in nearly every solution you will read. They are not clever tricks, without them some very ordinary code becomes surprisingly awkward.

Core idea. Destructuring unpacks values out of an array in one line. Spread copies a list into a new one. Together they let you swap two values, copy safely, and return several things at once.
Playground, this isn't a screenshot
two names, one array
const a = [1, 2, 3];
const b = a;        // NOT a copy
b.push(4);

console.log(a);     // [1,2,3,4]
console.log(b);     // [1,2,3,4]

Both names point at the same row of boxes.

spread makes a real copy
const a = [1, 2, 3];
const b = [...a];   // a NEW array
b.push(4);

console.log(a);     // [1,2,3]
console.log(b);     // [1,2,3,4]

Separate boxes. Changing one leaves the other alone.

swapping, in one line
[a, b] = [b, a];       // no temporary variable needed
[arr[i], arr[j]] = [arr[j], arr[i]];   // works on positions too
↑ play a little first, then dig in