Open In App

JavaScript – Swap Two Variables in JavaScript

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn about swapping 2 variables with Various Approaches.

Using destructing Assignment – Most Used

Here, we will be using a destructing Assignment. The destructing assignment makes it possible to unpack values from an array, object, or other properties into distinct variables.

JavaScript
let a = 40;
let b = 30;

console.log(`before swap a= ${a}`);
console.log(`before swap b= ${b}`);

// a would be swapped to b and b would be swapped to a
[b, a] = [a, b];

console.log(`after swap a= ${a}`);
console.log(`after swap b= ${b}`);

Output
before swap a= 40
before swap a= 30
after swap a= 30
after swap a= 40

Using Temporary variable

  • Let’s say we create a temp variable that stores the value of a variable A.
  • Then we copy the value of B to A (A would be overwritten).
  • Then we copy the value of temp to B (earlier value of A).
JavaScript
let a = 20;
let b = 10;
let temp;

console.log(`before swapping: a= ${a}`);
console.log(`before swapping b= ${b}`);

temp = a;
a = b;
b = temp;

console.log(`after swapping a= ${a}`);
console.log(`after swapping b= ${b}`);

Output
before swapping: a= 20
before swapping b= 10
after swapping a= 10
after swapping b= 20

Using Arithmetic Operations

  • Firstly, we add a + b to a (a would be greater than b as it is).
  • Now we subtract b from a so the value of b is now available to b
  • Now we subtract a with b again to a so a will have the value of B
JavaScript
let a = 10;
let b = 20;

console.log(`before swap a= ${a}`);
console.log(`before swap b= ${b}`);

a = a + b;//10=10+20 now a would be 30
b = a - b;//20=30-20 now b would be 10
a = a - b;//30=30-10 so a would be now 20

console.log(`after swap a= ${a}`);
console.log(`after swap b= ${b}`);

Output
before swap a= 10
before swap b= 20
after swap a= 20
after swap b= 10

Using XOR Bitwise Operator

the XOR bitwise operation is used to swap the values without the need for a temporary variable. This method takes advantage of the property that a ^ b ^ b is equal to a.

JavaScript
let a = 5;
let b = 10;

console.log("Before swapping: a =", a, "b =", b);

a = a ^ b;
b = a ^ b;
a = a ^ b;

console.log("After swapping: a =", a, "b =", b);

Output
Before swapping: a = 5 b = 10
After swapping: a = 10 b = 5


Next Article

Similar Reads