How do you swap two values and skip elements using array destructuring?
Array destructuring assigns the elements positionally, so swapping is a single expression rather than a temporary variable. Leaving a position empty skips it, and a rest element at the end collects everything 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 an element with an empty slot.
const [, second] = ["first", "second", "third"];
console.log(second); // "second"
// Collect the remainder with a rest element.
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
// Swap function arguments.
function swapArgs(x, y) {
[x, y] = [y, x];
return [x, y];
}
console.log(swapArgs("a", "b")); // ["b", "a"]The swap needs the parentheses around the array literal, and that is not optional style. Without them, the line starting with a bracket is parsed as the start of a property access on the previous statement, which is one of the classic automatic semicolon insertion traps. The parentheses turn it back into an expression.
The rest element always has to be last, because it collects everything remaining. That means you can capture the tail but not the head as a rest, and you cannot have two rest elements in one pattern.
One more pattern worth knowing is destructuring inside a loop, where the array holds pairs. You can destructure each pair directly in the loop header, which keeps the body readable and avoids indexing into the pair.