Open In App

JavaScript - Swap Two Variables in JavaScript

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
8 Likes
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.


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).

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

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.


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

Next Article

Similar Reads