# Techniques of swapping variables in JavaScript

## Quite handful for moving array elements up and down

Like I have been starting this series since last 2 post, I am currently in spree of giving tests. And so I came across this problem of moving array elements up and down based on button click on arrow up or arrow down. We won't be diving into the UI here but simple basic logic. Let's begin.

There are many ways to do make "a" as "b" and "b" as "a" - basic variable swapping. Here are few methods:

The oldest trick in the book. It takes help of an extra memory space "c" variable and stores the value of either "a" or "b" to it. Let's say it is "a". Then, the left over variable "b" is stored to "a" erasing the previous value of "a". Then "c" [previously "a"] is stored in "b".

The above approach requires extra memory space. So, we have in-place swapping. We store the sum of **"a+b"** into "a" making it 5. Then, we store 5 - 2 = 3 into "b". And finally 5 - 3 (new b) = 2 into "a".
This is where order of operation is important.

Although powerful but not that much readable, bitwise operation method. Here, we use XOR. What is bitwise and XOR?

In bitwise term: a = 3 = 11 b = 2 = 10

XOR makes similar bits 0 and different bits 1. So, a = 3 (decimal) = 11 (binary) b = 2 (decimal) = 10 (binary)

Then we see what the other 3 steps are doing here as explained in the image.

The 4th method is something that comes quite handy. This is swapping the variables using destructuring in JavaScript.

Here, we use array destructuring to swap the values of "a" and "b". Quite clean, quick, and handy.

The reason why this above method is quite handy because we can use it to move array elements up and down taking help of element indices.

So assume there is an array as shown and the initial index is 0. On certain event click of button, we can either do "moveUp" or "moveDown". Look at the image below for method.

A similar technique can be used to render list items in React if anytime we need feature to move the list items up and down the rendered lists. Add two button [up & down]. And use the desired method onClick as needed.

Thanks for reading. Hope you learnt something.