๐ฆ๐๐ฎ๐ฝ ๐ง๐๐ผ ๐ก๐๐บ๐ฏ๐ฒ๐ฟ๐ ๐ช๐ถ๐๐ต๐ผ๐๐ ๐ ๐ง๐ต๐ถ๐ฟ๐ฑ ๐ฉ๐ฎ๐ฟ๐ถ๐ฎ๐ฏ๐น๐ฒ
You want to swap two variables. Most people use a third variable. You do not need one.
Here are four ways to do it.
Method 1: Temporary Variable
- let temp = a
- a = b
- b = temp
Method 2: Addition and Subtraction
- a = a + b
- b = a - b
- a = a - b
Method 3: Destructuring
- [a, b] = [b, a]
Method 4: Bitwise XOR
- a = a ^ b
- b = a ^ b
- a = a ^ b
Pick the one you need for your project.
Source: https://dev.to/raja_b_0c9d242e2c26cf063b/swap-two-numbers-without-using-a-third-variable-1hje