Ask any question about JavaScript here... and get an instant response.
How do you use destructuring to swap two variables in JavaScript?
Asked on Oct 05, 2025
Answer
Destructuring in JavaScript allows you to easily swap two variables without using a temporary variable. Here's how you can do it:
<!-- BEGIN COPY / PASTE -->
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The code swaps the values of "a" and "b" using array destructuring.
- "[a, b] = [b, a];" is the key line where the swap happens.
- This method is concise and avoids the need for a temporary variable.
Recommended Links:
