At some point in their career, developers need to swap values. Most of the time we use the one plain old solution of “using a temporary variable”. Ugh, if only there was a better way. But wait! There is, and there’s not just one but many. In desperate times, we scour the web for solutions, find one, and copy it without ever wondering how this little snippet of code works. Lucky for you, now is the time to learn about how to swap values easily and efficiently, putting an end to your misery.

1) Using a temporary variable

Let’s just get the most obvious one out of the way.

function swapWithTemp(num1,num2){
  console.log(num1,num2)

  var temp = num1;
  num1 = num2;
  num2 = temp;

  console.log(num1,num2)
}

swapWithTemp(2.34,3.45)

2) Using Arithmetic Operators + and -

Yes, you are reading correctly. We can use some mathematics magic to swap your values.

function swapWithPlusMinus(num1,num2){
  console.log(num1,num2)

  num1 = num1+num2;
  num2 = num1-num2;
  num1 = num1-num2;

  console.log(num1,num2)
}

swapWithPlusMinus(2.34,3.45)

Whaaat!? Yep, so let’s see how it’s working. We get the sum of both numbers on line 4. Now, if we subtract one number from the sum then we get the other number right. That’s what we are doing on line number 5. Subtracting num2 from the sum which is stored in num1 variable will give the original num1 value which we store in num2. And similarly, we get assign num2 value in num1 on line 6.

Beware: There is also a one line swap with + and — floating around on the internet.

Here’s how it looks:

function swapWithPlusMinusShort(num1,num2){
  console.log(num1,num2)

  num2 = num1+(num1=num2)-num2;

  console.log(num1,num2)
}

swapWithPlusMinusShort(2,3)

The above program gives the expected result. The expression within ( ) stores num2 in num1 and then we subtract num1 — num2 which is nothing but subtracting num2 — num2 = 0. Hence, we get our result. But when we use floating-point numbers, we see some unexpected results.

Try playing with the values like below in your console.

function swapWithPlusMinusShort(num1,num2){
  console.log(num1,num2)

  num2 = num1+(num1=num2)-num2;

  console.log(num1,num2)
}

swapWithPlusMinusShort(2,3.1)

#web-development #javascript

10 Ways to Swap Values in JavaScript
15.95 GEEK