How to use XOR Bitwise Operator In Javascript
In this approach, the XOR (^) bitwise operator to interchange the values of the first and last elements in the array without using a temporary variable.
Syntax:
array[0] = array[0] ^ array[array.length - 1];
array[array.length - 1] = array[0] ^ array[array.length - 1];
array[0] = array[0] ^ array[array.length - 1];
Example: In this example we are using XOR operator to interchange the element in your given array.
const array = [1, 2, 3, 4, 5];
array[0] = array[0] ^ array[array.length - 1];
array[array.length - 1] = array[0] ^ array[array.length - 1];
array[0] = array[0] ^ array[array.length - 1];
console.log("Array after interchange:", array);
Output
Array after interchange: [ 5, 2, 3, 4, 1 ]
JavaScript Program to Swap First and Last Elements in an Array
In this article, we are going to learn about swaping the first and last elements in an array in JavaScript. Swaping the first and last elements in a JavaScript array refers to swapping their positions, effectively exchanging the values at these two distinct indices within the array.
There are several methods that can be used to interchange the first and last elements in an array in JavaScript, which are listed below:
Table of Content
- Using Temporary Variable
- Array Destructuring
- Using XOR Bitwise Operator
- Using splice() Method
- Using a for Loop
We will explore all the above methods along with their basic implementation with the help of examples.