Swapping 2 Numbers In More Than 2 Ways.
Tags: javascript, beginners, tutorial, productivity
Published: 2022-02-12 08:31:54

There is no programmer who did not come across the question:

> Write a program to swap two  numbers.

Swapping 2 numbers using a temporary variable is common. However, there are other ways of swapping. I am listing a few methods.

## Destructuring assignment

Before swapping numbers using _destructuring assignment_ which is introduced in [ES2015](https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015), let us understand what is it. 

```javascript
var a, b;

[a, b] = [33, 22, 11];

console.log(a, b) // 33 22
```
The `[a, b] = [33, 22, 11]` is the destructuring assignment that destructures array `[33, 22, 11]`. The first item __33__ is assigned on variable __a__, and the second item __22__ is assigned on variable __b__.

Knowing this, let us now swap.

```javascript
let a = 12, b = 24;

[a, b] = [b, a]; // destructuring assignment

console.log(`a = ${a}, b = ${b}`); // a = 24, b = 12
```

Stepwise breakdown of destructuring assignment:
1. A _temporary array_ `[b, a]` with value `[24, 12]` is created.
2. The destructuring occurs `[a, b] = [24, 12]`, where variable _a_ is assigned with value _24_ and variable _b_ is assigned with value _12_.

## Addition And Difference 

This method uses simple mathematical logic to solve the problem statement. 

```javascript
var a = 12, b = 24;

a = a + b; // a = 36
b = a - b; // b = 36 - 24 = 12
a = a - b; // a = 36 - 12 = 24

console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
```

However there are limitations to this method.
- We can swap integer numbers only
- The sum of `a = a + b` in the first step should be lower than `Number.MAX_SAFE_INTEGER`

> __Note:__ You can do this swapping in one line :
> ` num2 = num1 + ( num1 = num2 ) - num2; `
> I am using num1 and num2 for easy understanding

## Using Multiplication And Division

The method is again a logical technique. It's nearly same as previous method but just a grade up, i.e., it uses multiplication instead of addition and division instead of subtraction.

```javascript
var a = 12, b = 24;

a = a * b; // a = 288
b = a / b; // b = 288 / 24 = 12
a = a / b; // a = 288 / 12 = 24

console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
```

Let us discuss the limitations in this method:
- ZERO is the enemy of multiplication and division. Don't use this method if one of the number is _0_. It will result in `NaN`.
- Avoid `Infinity` and `-Infinity` as one of the number. The answer will again result in `NaN`.

> __Note:__ You can do this swapping in one line :
> ` num2 = num1 * ( num1 = num2 ) / num2; `
> I am using num1 and num2 for easy understanding

## Bitwise XOR operator

Let us revise the XOR operator before using this method. XOR operator returns true if 2 inputs are different. The table is shown below.

|a|b|a^b|
|---|---|---|
|0|0|0|
|0|1|1|
|1|0|1|
|1|1|0|

Using this logic we can swap 2 integers. The steps of swapping var a of value 5 and var b of value 9 are shown below.
1. Binary equivalent of the variables a and b are:
a = 5 = 0101 and b = 9 = 1001
2. Store the value of `a ^ b` into `a`.
```javascript
a = a ^ b
```
a|b|a = a ^ b
---|---|---
0|1|1
1|0|1
0|0|0
1|1|0
3.  Store the value of `a ^ b` into `b`.
```javascript
b = a ^ b
```
a|b|b = a ^ b
---|---|---
1|1|0
1|0|1
0|0|0
0|1|1
4.  Store the value of `a ^ b` into `a`.
```javascript
a = a ^ b
```
a|b|a = a ^ b
---|---|---
1|0|1
1|1|0
0|0|0
0|1|1
5. At this point variable __a__ holds the value __1001__ which is __9__ and variable __b__ holds the value __0101__ which is __5__. Hence we see the value is swapped.

```javascript
var a = 12, b = 24;

a = a ^ b; 
b = a ^ b; 
a = a ^ b; 

console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
```

Now let us see the limitations of this method:
- We cannot swap decimal point numbers as we just get the integer part of the number. The XOR assumes that the input is an integer and hence performs the calculations accordingly. But the floating-point number are not integers and are represented by IEEE 754 standard, which breaks the numbers in three parts: a sign bit, a group of bits representing an exponent, and another group representing a number between 1 (inclusive) and 2 (exclusive), the mantissa. Hence we get incorrect values.
- We cannot use `Infinity` and `-Infinity` as they are floating point integers and face the same problem as above.

## Using IIFE

An __IIFE__ or __Immediately Invoked Function Expression__ is a function that is executed just after the function is made. It can be used to do various jobs such as swapping 2 numbers.

```javascript
var a = 12, b = 24;

a = (function (b) {
    return b;
})(b, b = a)

console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
```

> I won't prefer this method. Just included for sharing knowledge. 

## Using Temporary Variable

This the most common method. Here a temporary variable is used to store one of the value for swapping.

```javascript
var a = 12, b = 24, temp;

temp = a; // temp = 12
a = b;    // a = 24
b = a;    // b = 12

console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
```

## Conclusion

I have created a gist with the swaps which can be found [here](https://gist.github.com/ishanbagchi/85a11bae754fe0afa3ab65386878fb7d).

There are lot more methods for swapping. I have listed a few preferable choice. If you know more techniques feel free to share them in the comments.