This page looks best with JavaScript enabled

Swap values between two variables

 ·   ·  ☕ 1 min read

Swapping variables is simple enough, but can it be any simpler?

Consider the below code -

1
2
let x = 1;
let y = 3;

To swap values -

1
2
3
4
5
6
let z = x;

x = y;
y = z;
console.log(x, y);
// 3 1

Applying our earlier knowledge about destructuring objects(/destructuring-assignments-in-javascript/), we can instead do -

1
2
3
4
5
6
let x = 1;
let y = 3;

[x, y] = [y, x];
console.log(x, y);
// 3 1

Beautiful, isn’t it?

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things