DEV Community

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)