DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Swap two variables without a 3rd : JavaScript
shivamkapasia0
shivamkapasia0

Posted on

Swap two variables without a 3rd : JavaScript

Destructuring assignment

Destructuring assignment (a feature of ES2015) lets you extract items of an array into variables.

let firstName = 'Shivam', secondName = 'Kapasia';
[firstName, secondName] = [secondName, firstName];
console.log('firstName: ' + firstName); // Kapasia
console.log('secondName: ' + secondName); // Shivam
Enter fullscreen mode Exit fullscreen mode

you can also swap two arrays like :

let array1 = [1,2,3], array2 = [3,4,5];
[array1, array2] = [array2, array1];
console.log(`${array1}`); // 3,4,5
console.log(`${array2}`); // 1,2,3
Enter fullscreen mode Exit fullscreen mode

I like the destructuring approach because it’s short and expressive: swapping is performed in just one statement. It works with any data type: numbers, strings, booleans, objects,arryas etc.

I recommend swapping variables using a destructuring assignment for most of the cases.

What’s your preferred way to swap variables?

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: