How do you swap two values and skip elements using array destructuring?
Array destructuring assigns the values by position, so swapping two values becomes one short expression instead of a temporary variable. Leaving a position empty skips that value, and a rest element at the end collects everything that you did not name.
// Swap without a temporary variable.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
// Skip a value with an empty slot.
const [, second] = ['first', 'second', 'third'];
console.log(second); // 'second'
// Collect the rest with a rest element.
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
// Swap the arguments of a function.
function swapArgs(x, y) {
[x, y] = [y, x];
return [x, y];
}
console.log(swapArgs('a', 'b')); // ['b', 'a']
The swap needs the round brackets around the array, and that is not only a style choice. Without them, a line that starts with a square bracket is read as the start of a property access on the line before it, which is one of the classic automatic semicolon insertion traps. The round brackets turn the line back into a single expression.
The rest element always has to be last, because it collects everything that is left. That means you can catch the tail with a rest element but you cannot catch the head, and you cannot have two rest elements in the same pattern.
One more pattern is worth knowing, and it is destructuring inside a loop where each value is a pair. You can pull the pair apart right in the loop, which keeps the body of the loop easy to read and saves you from counting through the numbers in the pair.