
How can I use destructuring to swap two variables in ES6?
Asked on Oct 04, 2025
Answer
Destructuring in ES6 allows you to swap two variables easily 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 code uses array destructuring to swap the values of "a" and "b".
- The expression "[a, b] = [b, a];" reassigns the values of "a" and "b" in one line.
- This method is concise and avoids the need for a temporary variable.
Recommended Links:
← Back to All Questions