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.

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
Discover more from Technbuzz.com
Subscribe to get the latest posts sent to your email.

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