How to use XOR Bitwise Operator In Javascript
Using the XOR bitwise operator, you can swap two elements without a temporary variable. This is done by sequentially applying XOR operations to the elements. This works because XORing a number twice with the same number returns the original number, effectively swapping the values.
Example: In this example we swaps the elements at index1 and index2 in the array arr using the XOR bitwise 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 ]
Swapping two array elements in a single line using JavaScript
In JavaScript, there exist many ways by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows.
Input: arr = { 10, 20, 40, 30 }
Output: arr = { 10, 20, 30, 40 }
// Swapped 30 and 40
Here are some common approaches:
Table of Content
- Using Destructuring Method
- Using XOR Bitwise Operator
- Using Array.splice