DEV Community

Heru Hartanto
Heru Hartanto

Posted on

How to swap two variable value without using temporary variable

Maybe you will find coding skill test that push you ability to swap value between two variables, some developer often using "the third var" technique

// use var instead of let :(
var a = 10;
var b = 14;
var temp = b;
b = a
a = temp
console.log(a, b);
Enter fullscreen mode Exit fullscreen mode

but some developer don't waste his line to create third variable, so this is what they do

let a = 10;
let b = 15;
[a,b] = [b,a]; // array destructuring 
console.log(a, b);
Enter fullscreen mode Exit fullscreen mode

even more, they can shorting their line with this rhapsodic technique

let [a,b] = [10,15];
[a,b] = [b,a];
console.log(a, b);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
zippytyro profile image
Shashwat Verma

haha interesting