How To Swap Two Values Without Temporary Variables Using JavaScript in 2023
A complete guide with answers for the interview
UPD: republishing with corrections
Swapping two values without using a temporary variable can be a tricky concept to grasp, but it is essential knowledge for a JavaScript developer. This guide will explain how to swap two values without using temporary variables in JavaScript and provide answers to common interview questions on the topic.
Swapping the value of two variables normally takes three lines and a temporary variable. What if I told you there was an easier way to do this with JavaScript?
There are two types of conditions for such a task. There is the classical condition, where we change two numbers. Then there is the more difficult task — change two of any type (string, float, object, other…).
Traditional Method
The goal is to swap the values of a
and b
(all types).
let a = 1,
b = 2,
c = 0;
c = a
a = b
b = c
Of course, we’ve introduced another variable, called c
, to temporarily store the original value of a
during the swap. But can we do it without c
? Yes, we can!
Solution for Integers Only
Let’s start with the first task — to change the two integers.
With mathematical operations
Arithmetic Method: One way to swap two values without using temporary variables is by using arithmetic operations, such as addition and subtraction:
a = a + b
b = a - b
a = a - b
or
a += b
b = a — b
a -= b
Bitwise XOR Method
Since these are integers, you can also use any number of clever tricks to swap without using a third variable. For instance, you can use the bitwise XOR operator:
let a = 5;
let b = 10;
a = a ^ b; // a = 15 (0101 ^ 1010 = 1111)
b = a ^ b; // b = 5 (1111 ^ 1010 = 0101)
a = a ^ b; // a = 10 (1111 ^ 0101 = 1010)
console.log('a:', a); // a: 10
console.log('b:', b); // b: 5
or
a ^= b;
b ^= a;
a ^= b;
This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article. I forgot to mention that this works reliably only with integers. I assumed the integer variables from question’s thread.
Hacks and tricks
Single line swapping with addition
a = b + (b=a, 0)
This solution uses no temporary variables, no arrays, only one addition, and it’s fast. In fact, it is sometimes faster than a temporary variable on several platforms. It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.
It works in two steps:
- (b=a, 0) sets b to the old value of a and yields 0
- a = b + 0 sets a to the old value of b
Another single line swapping:
b=a+(a=b)-b
Single line swapping with XOR
a = a^b^(b^=(a^b))
Solutions for All Types
And now on to the second task — to change the two variables with any types.
Classic one-line method
This trick uses an array to perform the swap. Take a second to wrap your head around it:
a = [b, b=a][0];
There are a few things happening here. If you’re having trouble understanding how or why this works, consider this explanation:
- We’re utilizing an array where the first index is the value of
a
and the second index is the value ofb
. a
is set to the value ofb
when the array is created.b
is set to the first index of the array, which isa
Another tricky one-line solution
Using ES6 self executing arrow functions:
b = (a=>a)(a,a=b);
or ES5+ immediately invoked function:
b = (function(a){ return a })(a, a=b);
ES6+ method. Destructuring Assignment
In modern JavaScript (ES6 and later), you can use destructuring assignment to swap two values without temporary variables.
[a, b] = [b, a]
Interview Questions and Answers
Why would you swap two values without using a temporary variable?
Answer: Swapping two values without using a temporary variable can be useful in optimizing memory usage, as it reduces the need for additional storage. This can be particularly beneficial in situations where memory is limited, such as in embedded systems or performance-critical applications.
What are the potential issues with the arithmetic method?
Answer: The arithmetic method can lead to integer overflow or underflow if the values being swapped are large or small enough to exceed the maximum or minimum representable values in JavaScript. Moreover, this method may not be suitable for non-numeric values, such as strings or objects.
How does the bitwise XOR method work?
Answer: The bitwise XOR method works by performing an exclusive OR operation on the binary representation of the two values. The result of the XOR operation is then used to calculate the original values by performing another XOR operation. Since XOR is a reversible operation, it allows the values to be swapped without the need for a temporary variable.
Can you use the destructuring assignment method to swap values of different data types?
Answer: Yes, the destructuring assignment method can be used to swap values of different data types, as it does not rely on arithmetic or bitwise operations. It works with any data type, including numbers, strings, and objects, making it a versatile method for swapping values without temporary variables.