HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How to swap two variables in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptswaptwohowvariables

Problem

In the past, swapping the values of two variables in JavaScript required an intermediate variable to store one of the values while swapping, which would result in something similar to this:
While this approach still works, there are more elegant and less verbose options available to us nowadays. For example, JavaScript ES6 introduced destructuring assignments, allowing individual array items to be assigned to variables in a single statement. Here's what that looks like:
Destructuring assignments are extremely useful in a handful of situations, including swapping two variables. To accomplish this, we can create an array from the two variables, then use a destructuring assignment to reassign them to each other:

Solution

let a = 10;
let b = 20;

let tmp;
tmp = a;
a = b;
b = tmp;


Destructuring assignments are extremely useful in a handful of situations, including swapping two variables. To accomplish this, we can create an array from the two variables, then use a destructuring assignment to reassign them to each other:

Code Snippets

let a = 10;
let b = 20;

let tmp;
tmp = a;
a = b;
b = tmp;
const [x, y] = [1, 2];
let a = 10;
let b = 20;

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

Context

From 30-seconds-of-code: swap-two-variables

Revisions (0)

No revisions yet.