In JavaScript, two elements of an array can be swapped without using a temporary variable. The most concise approach is array destructuring, which allows the values to be exchanged in a single line.
- Swaps two elements using their array indexes.
- Array destructuring avoids the need for a temporary variable.
- The approach works with numbers, strings, and other data types.
Approach 1: Using Destructuring Assignment
Destructuring assignment provides a simple way to swap two array elements in a single line. The values on the right-hand side are assigned to the positions on the left-hand side in reverse order.
Syntax:
[a[m], a[n]] = [a[n], a[m]];Here, m and n are the indexes of the elements to be swapped.
Example: Swap the elements at indexes 3 and 4 using array destructuring.
let arr = [1, 2, 3, 5, 4];
// Swap elements at index 3 and index 4
[arr[3], arr[4]] = [arr[4], arr[3]];
console.log(arr);
Output
[ 1, 2, 3, 4, 5 ]
Approach 2: Using XOR Bitwise Operator
The XOR (^) operator can swap two numeric elements without using a temporary variable. It uses three XOR operations to exchange the values.
Example: Swap the elements at indexes 1 and 3 using the XOR operator.
let arr = [1, 2, 3, 4, 5];
let index1 = 1;
let index2 = 3;
arr[index1] ^= arr[index2];
arr[index2] ^= arr[index1];
arr[index1] ^= arr[index2];
console.log(arr);
Output
[ 1, 4, 3, 2, 5 ]
Approach 3: Using Array.splice()
The splice() method can be used to replace elements at specific positions. By extracting and rearranging the required elements, we can swap their positions within the array.
Example: Swap the elements at indexes 0 and 1.
let array = [1, 2, 3, 4];
[array[0], array[1]] = [array[1], array[0]];
console.log(array);
Output
[ 2, 1, 3, 4 ]
Note: Array destructuring is the preferred approach for swapping two array elements because it is concise, readable, and works with different data types.