Swap Variable Values Without a Temporary Variable with Array Destructuring

A common interview question is "Swap the variable values."

Usually the solution involves a temporary variable. But we can solve this easily with a destructuring trick.

We can use destructuring to swap the values of two variables without the need for a temporary variable:

let a = 1;
let b = 2;

console.log(a); // 1
console.log(b); // 2

[a, b] = [b, a];

console.log(a); // 2
console.log(b); // 1

Now you have the most elegant solution. 😉

JavaScriptJSTricks
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.