facebook-squared twitter-squared rss-squared gplus-squared



June 2018



Swapping variables values hasn’t been that easy in JavaScript

Written by on 10 June 2018

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 - technbuzz.com

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

Leave a Reply

%d bloggers like this: