DEV Community

loading...

How to swap 2 variables in javascript

pestrinmarco profile image Marco Pestrin ・1 min read

Normally to swap two variables you need a temporary variable because when the first variable is reassigned you lose the value.

let a = 'apple';
let b = 'orange';

let tmp = a;
a = b;
b = temp;
Enter fullscreen mode Exit fullscreen mode

We have the syntax available to perform a swap without need an intermediate variable.

let a = 'apple';
let b = 'orange';

[a, b] = [b, a];

console.log(a); // orange
console.log(b); // apple
Enter fullscreen mode Exit fullscreen mode

Javascript destructuring enable variable swapping without need an intermediate variable.

Cheers mates!

Discussion

pic
Editor guide