Ask any question about JavaScript here... and get an instant response.
How can I use destructuring to swap values of two variables in JavaScript?
Asked on Oct 23, 2025
Answer
Destructuring in JavaScript provides a concise way to swap the values of two variables without needing 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 array destructuring syntax "[a, b] = [b, a]" allows you to swap the values of "a" and "b" directly.
- This method is concise and eliminates the need for a temporary variable.
- The console.log statements confirm that the values have been swapped.
Recommended Links:
