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.

Javascript
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.

Similar Reads

Using Temporary Variable

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....

Array Destructuring

In this approach we are using Array destructuring assigns values from an array to variables, swapping the first and last elements....

Using XOR Bitwise Operator

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....

Using splice() Method

In this approach, splice() method is used to replace the last element with the first element, and the result is assigned back to the first position in the array. This effectively interchanges the values 12 and 55 in the array....

Using a for Loop

Using a for loop, the function swaps the first and last elements of an array by iterating through the array. When the loop index is zero, it temporarily stores the first element, assigns the last element to the first position, and places the stored element at the last position....