Swapping variables values hasn’t been that easy in JavaScript

Now with new language features Javascript swap variable values very easily.

While doing laundry a thought popped up in my mind and how it relates to JavaScript.

Imagine the following picture.

Picture of washing machine and dryer are already occupied, the clothes inside needs to be swapped an example for JavaScript swap values in es6 -

Now how you could swap clothes from these two machines. You do need a temporary container to hold clothes from side and make the transformation happen. Same the case with Programming (although this tutorial isn’t limited to JavaScript only)

let a = 123;
let b = 456;
let temp = a;
a = b;
b = temp;

console.log(a);     //456
console.log(b);     //123

Here the temp variable does the job of temporary container. But the new JavaScript destructuring assignment syntax makes even easier and less confusing.

let a = 123;
let b = 456;
[a,b] = [b,a];

console.log(a,b);     // 456 123

One reply on “Swapping variables values hasn’t been that easy in JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.