DEV Community

Cover image for Swap two variables without a 3rd : JavaScript
shivamkapasia0
shivamkapasia0

Posted on

3 2

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?

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay