DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Edited on

How to swap 2 variables in javascript

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!

Top comments (0)