Swap two variables without a 3rd : JavaScript
shivamkapasia0
Posted on October 31, 2021
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
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
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?
💖 💪 🙅 🚩
shivamkapasia0
Posted on October 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.