Swapping variables is a common task in programming, and there are several ways to do it without using a third variable. In this post, we'll explore five different methods in JavaScript, each with a detailed explanation.
1. Addition and Subtraction
This method involves simple arithmetic operations:
a = a + b;
b = a - b;
a = a - b;
console.log('After Addition and Subtraction:');
console.log('a:', a); // 40
console.log('b:', b); // 20
Explanation:
a = a + b;
combines the values of a
and b
and stores the result in a
.
b = a - b;
subtracts the new value of b
(which is a
) from a
to get the original value of a
.
a = a - b;
subtracts the new value of b
(original a
) from a
to get the original value of b
.
2. Multiplication and Division
Another arithmetic method, but using multiplication and division. Note that this method assumes a
and b
are non-zero to avoid division by zero:
a = 20;
b = 40;
a = a * b;
b = a / b;
a = a / b;
console.log('After Multiplication and Division:');
console.log('a:', a); // 40
console.log('b:', b); // 20
Explanation:
a = a * b;
multiplies the values of a
and b
and stores the result in a
.
b = a / b;
divides the new value of a
by b
to get the original value of a
.
a = a / b;
divides the new value of a
by the new value of b
to get the original value of b
.
3. Using Bitwise XOR
Bitwise operations can also be used to swap variables:
a = 20;
b = 40;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log('After Bitwise XOR:');
console.log('a:', a); // 40
console.log('b:', b); // 20
Explanation:
a = a ^ b;
stores the result of the bitwise XOR of a
and b
in a
.
b = a ^ b;
stores the result of the bitwise XOR of the new a
and b
(which is the original a
) in b
.
a = a ^ b;
stores the result of the bitwise XOR of the new a
and b
(which is the original b
) in a
.
4. Using Array Destructuring
A more modern and elegant approach in JavaScript uses array destructuring:
a = 20;
b = 40;
[a, b] = [b, a];
console.log('After Array Destructuring:');
console.log('a:', a); // 40
console.log('b:', b); // 20
Explanation:
[a, b] = [b, a];
swaps the values of a
and b
using array destructuring assignment. This is a concise and readable way to swap variables in modern JavaScript.
5. Compound Assignment Swap (Single Line Swap)
This clever method uses a
combination of arithmetic and assignment in a single line:
a = 20;
b = 40;
a = a + b - (b = a);
console.log('After Compound Assignment Swap:');
console.log('a:', a); // 40
console.log('b:', b); // 20
Explanation:
a = a + b - (b = a);
may look complex but it follows a specific sequence of operations due to how JavaScript evaluates expressions. Here's what happens:
-
(b = a)
assigns the value ofa
tob
. - Then,
a + b - (b = a)
becomesa + a - a
, which effectively swaps the values ofa
andb
.
In summary, each of these methods achieves the same result of swapping variables a
and b
without using a third variable, showcasing different techniques in JavaScript.
Top comments (0)