JavaScript › Destructuring, Spread & Rest
How can you use destructuring to swap two variables without a temporary variable?
AdvancedAnswer
Array destructuring evaluates the right-hand side array literal fully before assigning, so wrapping both variables in a temporary array and destructuring back swaps them in a single expression.
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1Real-world example A classic interview trick question, occasionally useful in real sorting/swapping algorithm code.