How to use Temporary Variable In Javascript
Interchanging first and last array elements in JavaScript involves storing the first element in a temporary variable, and then swapping values between the first and last elements.
Syntax:
let temp = arr1[0];
arr1[0] = arr1[arr1.length - 1];
arr1[arr1.length - 1] = temp;
Example: In this example, we are using a temp variable to interchange 1st index value with the last index value of our array.
let arr1 = [10, 20, 30, 40, 50];
let temp = arr1[0];
arr1[0] = arr1[arr1.length - 1];
arr1[arr1.length - 1] = temp;
console.log("Array after interchange:", arr1);
Output
Array after interchange: [ 50, 20, 30, 40, 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.
Contact Us