Advertisement
Advanced JavaScript, Destructuring, Spread & Rest

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

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How would you have swapped variables before destructuring existed?
Related topics