JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Q&A Logo

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:
  • 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.
✅ Answered with JavaScript best practices.
← Back to All Questions