Swap two variables without a temp variable in JavaScript
Beginner · 3 min read
Swapping two values, so a holds what b had and b holds what a had, comes up all the time: sorting, shuffling, flipping two cards in a game, reversing a list. The classic way uses a third "temporary" variable. In this tutorial you will learn two ways to do it without one, and why only one of them belongs in real code.
You will write swapModern(a, b) and swapArithmetic(a, b). Each returns the two values swapped, as an array. You need to know what a variable, a function and an array are. Destructuring is explained below.
Why a swap needs care
The obvious attempt doesn't work:
let a = 1;
let b = 2;
a = b; // a is now 2
b = a; // b is now 2 as well
console.log(a, b); // 2 2
The first line overwrites a, so its old value is gone before b can get it. The classic fix saves it first:
let a = 1;
let b = 2;
const temp = a;
a = b;
b = temp;
console.log(a, b); // 2 1
That works, but it takes three lines and an extra name.
Destructuring
Destructuring lets you unpack an array into variables in one go:
const [first, second] = ['x', 'y'];
console.log(first, second); // x y
The left side is a pattern: "put item 0 in first and item 1 in second". You can do the same with variables that already exist, which is the key to the swap.
Here is the exercise. Try it yourself first if you like, or follow the steps.
21 Swap two variables without a third
easyExchange the values of two variables. Do it with destructuring, and also with arithmetic, and say which you would actually ship.
Stuck? Three hints, smallest first
- 1. Destructuring does it in one line:
[a, b] = [b, a]. - 2. The arithmetic trick,
a = a + bthenb = a - bthena = a - b, needs no extra variable but only works for numbers. - 3. The arithmetic version can lose precision on very large numbers. That is why nobody ships it.
Step 1: swap with destructuring
[b, a] on the right builds a new array from the current values, 2 and 1. Then the left side unpacks it back into a and b. Since the right side is built before anything is assigned, nothing gets overwritten too early.
function swapModern(a, b) {
[a, b] = [b, a];
return [a, b];
}
console.log(swapModern(1, 2)); // [ 2, 1 ]
console.log(swapModern('first', 'second')); // [ 'second', 'first' ]
console.log(swapModern(1, 'one')); // [ 'one', 1 ]
It works for numbers, text, a mix of both, or anything else, because it only moves values around. It doesn't do any maths on them.
Step 2: swap with arithmetic
There is an older trick that uses only + and -. Follow it with a = 1 and b = 2:
function swapArithmetic(a, b) {
a = a + b; // a = 3 (the total)
b = a - b; // b = 3 - 2 = 1 (the old a)
a = a - b; // a = 3 - 1 = 2 (the old b)
return [a, b];
}
console.log(swapArithmetic(1, 2)); // [ 2, 1 ]
a holds the total for a moment, so neither value is lost. It is a clever puzzle, and it turns up in interviews. But it has two problems.
Step 3: the first problem, numbers only
Try it with text:
console.log(swapArithmetic('first', 'second')); // [ NaN, NaN ]
+ on two strings joins them into 'firstsecond', and subtracting text gives NaN (Not a Number). The trick only works for numbers.
Step 4: the second problem, big numbers
JavaScript numbers are exact only up to Number.MAX_SAFE_INTEGER, which is 9007199254740991. Above that, some whole numbers can't be stored and get rounded to a neighbor. The first line of the trick adds the two values, so the total can go over the limit even when both inputs are fine.
const big = Number.MAX_SAFE_INTEGER;
const [x, y] = swapArithmetic(big, 2);
console.log(x, y); // 2 9007199254740990
console.log(y === big); // false
console.log(swapModern(big, 2)[1] === big); // true
y should be 9007199254740991. It is off by one, and nothing warns you. Destructuring has no such problem, because it never adds anything.
Which one to use
Use destructuring. It works for every type, it can't lose precision, and [a, b] = [b, a] says exactly what it does. The arithmetic version is worth understanding, but not shipping.
The full solution
The complete answer has both functions, swaps numbers, text and mixed values, and ends with the big-number case where the arithmetic version goes wrong. Press Run to see the output.
// The one you should write.
function swapModern(a, b) {
[a, b] = [b, a];
return [a, b];
}
// The interview-trivia version. Numbers only, and it can overflow.
function swapArithmetic(a, b) {
a = a + b;
b = a - b;
a = a - b;
return [a, b];
}
console.log('destructuring:', swapModern(1, 2));
console.log('arithmetic :', swapArithmetic(1, 2));
// Works for anything, because it does not do maths:
console.log('text :', swapModern('first', 'second'));
console.log('mixed :', swapModern(1, 'one'));
// Where the arithmetic version quietly goes wrong:
const big = Number.MAX_SAFE_INTEGER;
const [x, y] = swapArithmetic(big, 2);
console.log('big numbers swapped:', x, y, '-- expected 2 and', big);
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('numbers swap', swapModern(1, 2), [2, 1]);
test('text swaps', swapModern('first', 'second'), ['second', 'first']);
test('mixed types swap', swapModern(1, 'one'), ['one', 1]);
test('arithmetic works for small numbers', swapArithmetic(1, 2), [2, 1]);
test('but loses precision at the safe-integer limit', y === big, false);
test('destructuring handles the same case fine', swapModern(big, 2)[1], big);
The last two assertions are the argument. Beyond Number.MAX_SAFE_INTEGER, a + b cannot be represented exactly, so the arithmetic swap returns a number that is close but wrong — silently. Destructuring moves references and cannot have that problem, works for any type, and reads as what it means.
Common mistakes
- Assigning one variable to the other directly.
a = b; b = a;leaves both holding the same value. - Using the arithmetic trick on non-numbers. Strings join instead of adding, and you get
NaN. - Starting a line with
[a, b] = …after a line with no semicolon. JavaScript may join the two lines and read the brackets as part of the line above. End the line before with a semicolon.
Try it yourself
- Write
swapItems(array, i, j)that swaps two items in an array using destructuring:[array[i], array[j]] = [array[j], array[i]]. - Use it to reverse an array in place by swapping the first and last, then the second and second-last, and so on.
- Swap three variables in one line so
agetsb,bgetscandcgetsa.