Summary of ten methods of exchanging values in JavaScript

  • 2021-08-06 20:35:16
  • OfStack

Preface

In the development process, we need to exchange values. We are all using a simple solution: "temporary variables". But there are better ways, and there are not only one, but many. Sometimes we search for solutions online, copy and paste when we find them, but we never think about how this little piece of code works. Now it's time to learn how to exchange values easily and efficiently.

1 Using temporary variables

First, the simplest one.


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 Use the arithmetic operators + and-

You can also use some mathematical magic to exchange 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)

Let's see how it works. We get the sum of the two numbers in line 4. Now, if you subtract one number from the sum, then the other number is correct. This is what line 5 does. Subtracting num2 from the sum stored in num1 variables yields the original num1 value stored in num2. Similarly, get the value of num2 in num1 on line 6.

Caution: There is also a one-line code scheme interchangeable with + and-, however. . .

It goes like this:


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

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

 console.log(num1,num2)
}

swapWithPlusMinusShort(2,3)

The above code gives the expected result. The expression in () stores num2 in num1, then subtracts num1-num2, and does nothing but subtract num2-num2 = 0, so you get the result. However, when using floating-point numbers, you will see 1 unexpected results.

Try executing the following code and see the results:


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

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

 console.log(num1,num2)
}

swapWithPlusMinusShort(2,3.1)

3 Use only the + or-operator

You can achieve the same result by using + and-at the same time only by using the + operator.

Look at the following code:


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

 num2 = num1 + (num1=num2, 0)

 console.log(num1,num2)
}

//Try with - operator
swapWithPlus(2.3,3.4)

The above code is effective, but readability is sacrificed. In line 4 (), we assign num1 to num2, and the next 0 is the return value. In short, the operation logic in line 4 is as follows:


num2 = num1 + 0 
=> num2 = num1.

So we got the correct result.

Note: Some JavaScript engines may optimize the above code to ignore + 0.

4 Use the arithmetic operators * and/

Let's play more tricks with * and/operators.

The principle is the same as the previous method, but there are some minor problems.


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

 num1 = num1*num2;
 num2 = num1/num2;
 num1 = num1/num2;

 console.log(num1,num2)
}

swapWithMulDiv(2.34,3.45)

Same as the previous 1 method. First, the product of two numbers is obtained and stored in num1. Then, on line 5, divide num2 with this result to get the first number, and repeat this process to get the second number.

Now you are a mathematician.

But where is the little problem?

Let's try 1:


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

 num1 = num1*num2;
 num2 = num1/num2;
 num1 = num1/num2;

 console.log(num1,num2)
}

// Try to change the value of the number and see what happens 
swapWithMulDiv(2.34,0)

Instead of swapping our values, we got a strange NaN. What happened? If you remember the math class in elementary school, you will remember not to divide by 0, because it is meaningless.

Then look at other problems with this method and look at the following code:


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

 num1 = num1*num2;
 num2 = num1/num2;
 num1 = num1/num2;

 console.log(num1,num2)
}
// See what happens 
swapWithMulDiv(2.34,Infinity)

Yes, it's NaN again. Because you can't use Infinity to remove any value, it is undefined.

But I want to try again:


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

 num1 = num1*num2;
 num2 = num1/num2;
 num1 = num1/num2;

 console.log(num1,num2)
}

// What will happen 
swapWithMulDiv(2.34,-Infinity)

The result of-Infinity is the same as the previous code for one reason.

Facts have proved that even if you are an excellent "mathematician", there are times when you can't do anything.

The following is a shorter version of value exchange with * and/, which still has the same problem:


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)
0

The above code is similar to the shorter code when exchanging with + and-. Assign num2 to num1, and then the calculus logic in line 4 is as follows:


num2 = num1 * num2 / num2
 => num2 = num1

So the two values are interchangeable.

5) Use only the * or/operator


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

 num2 = num1 * (num1=num2, 1)

 console.log(num1,num2)
}

//Try with / and ** operator
swapWithMul(2.3,3.4)

The above program is effective, but readability is sacrificed. In line 4 (), we assign num1 to num2, with the return value next to 1. In short, the logic in Line 4 is as follows:


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)
3

In this way, we get the result.

6 Use Bitwise XOR (XOR).

XOR is used for binary bit operations. When there are two different inputs, its result is 1, otherwise it is 0.

X Y X^Y
1 1 0
1 0 1
0 1 1
0 0 0

Understand how it works first!


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)
4

The 4-digit binary number of 10- > 1010

The 4-digit binary number of 1- > 0001

Now:


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)
5

The two values are exchanged.

Let's look at another example:


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)
6

Hmm? ? Where is the value exchanged? We just get the integer part of the number, which is the problem. XOR assumes that the input is an integer, so the calculation is performed accordingly. But floating-point numbers are not integers, but are represented by the IEEE 754 standard, which divides numbers into three parts: sign bits, a group of bits representing exponents, and a group of bits representing mantissas. The digits are numbers between 1 (inclusive) and 2 (exclusive). So the resulting value is incorrect.

Another example:


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

 num1 = num1^num2;
 num2 = num1^num2;
 num1 = num1^num2;

 console.log(num1,num2)
}
//  Try  infinities  And integer values .
swapWithXOR(-Infinity,Infinity)

Not surprisingly, we didn't get the expected results. This is because both Infinity and Infinity are floating-point numbers. As we discussed earlier, floating-point numbers are a problem for XOR.

7 Use bitwise identical OR (XNOR)

It is used for binary bit operation, but it is just the opposite of XOR. When there are two different inputs, the result of XNOR is 0, otherwise it is 1. JavaScript does not have an operator that executes XNOR, so the NOT operator is used to negate the result of XOR.

X Y XNOR
1 1 1
1 0 0
0 1 0
0 0 1

Understand how it works first:


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

 num1 = ~(num1^num2);
 num2 = ~(num1^num2);
 num1 = ~(num1^num2);

 console.log(num1,num2)
}

// You can try negative values 
swapWithXNOR(10,1)

The 4-digit binary number of 10- > 1010

The 4-digit binary number of 1- > 0001

Line 4:


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)
9

Since this is a negative number, you need to convert it back to binary and calculate the complement of 2 to get the decimal value, for example:


-12 => 1100 
 => 0011 + 1 
 => 0100

Line 5:


num2 = ~(num1 ^ num2) 
 => ~(0100 ^ 0001) 
 => ~(0101) 
 => ~5 
 => -6-6 
 => 0110 
 => 1001 + 1
 => 1010 
 => 10

Line 6:


num1 = ~(num1 ^ num2) 
 => ~(0100^ 1010) 
 => ~(1110) 
 => ~14 
 => -15-15 
 => 1111 
 => 0000 + 1 
 => 0001 
 => 1

It took 1 time, but the values were exchanged. Unfortunately, it encounters the same problem as XOR, and cannot handle floating-point numbers and infinity.

Try the following values:


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

 num1 = ~(num1^num2);
 num2 = ~(num1^num2);
 num1 = ~(num1^num2);

 console.log(num1,num2)
}

swapWithXNOR(2.3,4.5)

8 Assigning Values in Arrays

This is a 1-line skill. It takes only one line of code to exchange, and more importantly, it requires no mathematical operation, only the basic knowledge of arrays. But it may look strange.

Let's look at its actual effect first:


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

 num2 = [num1, num1 = num2][0];

 console.log(num1,num2)
}

swapWithArray(2.3,Infinity)

num1 is stored in subscript 0 of the array, and num2 is allocated to num1 and num2 is stored in subscript 1. In addition, we just access [0] and store the num1 values in the array in num2. And you can swap anything you want here, such as integers, floating-point numbers (including infinities), and strings. It looks neat, but it loses the clarity of the code here.

9 Using Deconstruction Expressions

This is the function of ES6. This is the simplest of all methods. It takes only 1 line of code to complete the exchange:


let num1 = 23.45;
let num2 = 45.67;

console.log(num1,num2);

[num1,num2] = [num2,num1];

console.log(num1,num2);

10. Use the function expression called immediately (IIFE)

This is the strangest one. Simply put, IIFE is a function that executes immediately after definition.

You can use it to exchange two values:


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

 num1 = (function (num2){ return num2; })(num2, num2=num1)

 console.log(num1,num2)
}

swapWithIIFE(2.3,3.4)

In the above example, a function is called immediately on line 4. The last parenthesis is the parameter of the function. The second parameter assigns num1 to num2 and returns only the first parameter, but this exchange method is inefficient.

Summarize

This paper discusses many methods for exchanging values in JavaScript. Hope to help you!


Related articles: