Array Destructuring
In this approach we are using Array destructuring assigns values from an array to variables, swapping the first and last elements.
Syntax:
[array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];
Example:
let array = [10, 2, 5, 12, 7];
[array[0], array[array.length - 1]] = [array[array.length - 1], array[0]];
console.log("Array after swapping : " + array);
Output
Array after swapping : 7,2,5,12,10
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.