DEV Community

loading...

How to swap two variable value without using temporary variable

Heru Hartanto
Frontend developer based in Jakarta
・1 min read

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

Discussion (2)

Collapse
bacloud14 profile image
bacloud14 • Edited

that's a language feature, what about a mental hack ? x) here it is:

a = 1
b = 2
a = a + b
b = a - b
a = a - b
Enter fullscreen mode Exit fullscreen mode

Care about overflows though :)

Collapse
zippytyro profile image
Shashwat Verma

haha interesting

Forem Open with the Forem app