JavaScript - Use Arrays to Swap Variables
Last Updated :
23 Jan, 2025
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.
JavaScript
let x = 5;
let y = 10;
[x, y] = [y, x];
console.log(x);
console.log(y);
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.
JavaScript
let a = 1, b = 2, c = 3;
[a, b, c] = [c, a, b];
console.log(a);
console.log(b);
console.log(c);
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:
JavaScript
let x = 5;
let y = 10;
let temp = x;
x = y;
y = temp;
console.log(x);
console.log(y);
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.
JavaScript
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);
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.
JavaScript
const a = [10, 20, 30];
[a[0], a[2]] = [a[2], a[0]];
console.log(a);
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.
JavaScript
const obj = { x: 1, y: 2 };
[obj.x, obj.y] = [obj.y, obj.x];
console.log(obj);
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.
JavaScript
function swap([x, y]) {
return [y, x];
}
let [a, b] = swap([5, 10]);
console.log(a);
console.log(b);
This approach is modular and keeps your code clean, especially for repeated swaps.
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics