Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Swap First and Last Elements in an Array
Next article icon

JavaScript Program to Swap First and Last Elements in an Array

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
  • Using push() and shift() Methods

We will explore all the above methods along with their basic implementation with the help of examples.

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.

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 ] 

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:

JavaScript
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 

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.

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.

JavaScript
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 ] 

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.

Syntax:

Array.splice( index, remove_count, item_list )

Example: In this example we are using the above-explained approach.

JavaScript
let myArray = [12, 22, 33, 44, 55]; myArray[0] = myArray.splice(myArray.length - 1, 1, myArray[0])[0]; console.log(myArray); 

Output
[ 55, 22, 33, 44, 12 ] 

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.

Example:

JavaScript
function swapFirstLast(arr) {     if (arr.length > 1) {         for (let i = 0; i < arr.length; i++) {             if (i === 0) {                 let temp = arr[i];                 arr[i] = arr[arr.length - 1];                 arr[arr.length - 1] = temp;                 break;             }         }     }     return arr; }   console.log(swapFirstLast([1, 2, 3, 4, 5])); // [5, 2, 3, 4, 1] console.log(swapFirstLast([10, 20, 30]));    // [30, 20, 10] console.log(swapFirstLast([7]));             // [7] 

Output
[ 5, 2, 3, 4, 1 ] [ 30, 20, 10 ] [ 7 ] 

Using push() and shift() Methods

In this approach, we use the push() method to add elements to the end of the array and the shift() method to remove the first element. We can use these methods to swap the first and last elements of the array.

Example: In this example, we are using push() and shift() methods to interchange the first and last elements of the array.

JavaScript
let array = [1, 2, 3, 4, 5]; let firstElement = array.shift(); let lastElement = array.pop(); array.unshift(lastElement); array.push(firstElement); console.log("Array after interchange:", array); 

Output
Array after interchange: [ 5, 2, 3, 4, 1 ] 

Next Article
JavaScript Program to Swap First and Last Elements in an Array

V

vishalkumar2204
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Program

Similar Reads

    Javascript Program to Interchange elements of first and last rows in matrix
    Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1The approach is very
    2 min read
    JavaScript Program to Interchange Elements of First & Last in a Matrix Across Columns
    We are given a matrix and we have to interchange the elements of the first and last columns with each other in a matrix. Example: Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6Table of Content Using the swapping logicUsing forEach methodUsing the swapping logicIn
    3 min read
    JavaScript Program for Insertion Sort
    What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
    4 min read
    JavaScript Program to Rearrange Array Alternately
    Rearranging an array alternately means, If we have a sorted array then we have to rearrange the array such that the first largest element should come at index-0(0-based indexing), first smallest element should come at index-1, similarly, second largest element should come at index-3 and second small
    7 min read
    JavaScript Program to Find Minimum Number of Swaps to Sort Array
    The minimum number of swaps to sort an array is the smallest quantity of element swaps needed to arrange the array in ascending or descending order. This minimizes the number of exchanges and is a key metric in sorting algorithms, as reducing swaps often improves efficiency and performance when orga
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences