Back to results for “Destructuring”
JavaScript › Destructuring, Spread & Rest

How can you use destructuring to swap two variables without a temporary variable?

Advanced

Answer

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 1
Real-world example A classic interview trick question, occasionally useful in real sorting/swapping algorithm code.

Common follow-ups: How would you have swapped variables before destructuring existed?