JavaScript - Use Arrays to Swap Variables
Here are the different methods to swap variables using arrays in JavaScript
1. Using Array Destructuring
Array destructuring is the most efficient and modern way to swap variables in JavaScript. This method eliminates the need for a temporary variable.
let x = 5;
let y = 10;
[x, y] = [y, x];
console.log(x);
console.log(y);
Output
10 5
Here, the array [y, x] is unpacked, and the values of x and y are swapped in a single step.
2. Swapping More Than Two Variables
You can also use array destructuring to swap multiple variables.
let a = 1, b = 2, c = 3;
[a, b, c] = [c, a, b];
console.log(a);
console.log(b);
console.log(c);
Output
3 1 2
This approach works seamlessly for swapping multiple variables in a single line of code.
3. Using Temporary Variable (Traditional Approach)
Before destructuring was introduced, a temporary variable was commonly used for swapping:
let x = 5;
let y = 10;
let temp = x;
x = y;
y = temp;
console.log(x);
console.log(y);
Output
10 5
While effective, this approach is less concise and involves creating an additional variable.
4. Using Arithmetic Operator (Swapping Without a Temporary Variable)
You can also swap two numbers using arithmetic operations. This approach avoids using an array but may not work well for large numbers due to potential overflow.
let x = 5;
let y = 10;
x = x + y; // x becomes 15
y = x - y; // y becomes 5
x = x - y; // x becomes 10
console.log(x);
console.log(y);
Output
10 5
While clever, this method is less readable and can introduce bugs in certain edge cases.
5. Swapping Variables in Arrays
If you’re working with arrays, you can use destructuring to swap elements directly.
const a = [10, 20, 30];
[a[0], a[2]] = [a[2], a[0]];
console.log(a);
Output
[ 30, 20, 10 ]
This is especially useful when you need to rearrange elements in an array.
6. Swapping Variables in Objects
Although this doesn’t involve arrays directly, you can use destructuring with objects to swap values between two properties.
const obj = { x: 1, y: 2 };
[obj.x, obj.y] = [obj.y, obj.x];
console.log(obj);
Output
{ x: 2, y: 1 }
This is a powerful way to manipulate object properties while swapping values.
7. Combining Swapping with Functions
Swapping variables using arrays can also be combined with functions to make the code reusable.
function swap([x, y]) {
return [y, x];
}
let [a, b] = swap([5, 10]);
console.log(a);
console.log(b);
Output
10 5
This approach is modular and keeps your code clean, especially for repeated swaps.