# How can I swap two integers without temporary variables using JavaScript code?

Asked by

Ranimi23 (

1911)
October 16th, 2012

Observing members:
0
Composing members:
0
## 7 Answers

This is a trick using the exclusive or operator ^ that was used when computers were short on memory.

a = (a ^ b) /* a^b, b */

b = (a ^ b) /* a^b, a */

a = (a ^ b) /* b, a */

You can also do it using subtraction for numeric values

a = a – b /* a – b, b */

b = b -a /* a-b, a */

a = b – a /* b, a */

The second step for the subtraction should be b = a + b

So it should be in JS:

a = a ^ b;

b = a ^ b;

a = a ^ b;

How about:

A = A + B

B = A – B

A = A – B

You can’t forget that values of A and B are changing as you encounter these equations. So these equations would totally fail as “simultaneous equations”, but they work in series as the computer operates them.

A = A * B

B = A / B

A = A / B

So, for example, if you start out that A = 2; B = 7:

A = A * B = 2 * 7 = 14

B = A / B = 14 / 7 = 2

A = A / B = 14 / 2 = 7

side note:

although it is doable without a temporary variable, I find

var temp = a;

a = b;

b = temp;

much more obvious and I prefer obvious over clever most of the time when reading other people’s code.

The advantage of using exclusive or for a computer is that there is no chance of overflow or, as in the case of division, loss of accuracy due to rounding.

## Answer this question

This question is in the General Section. Responses must be helpful and on-topic.