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

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