Reverse an Array in JavaScript without using Inbuilt Function

In JavaScript, there are numerous ways to reverse an array such as using the inbuilt function reverse() or creating an auxiliary array and copying the values of the original array into this auxiliary array in reverse order, and so on.

But, to solve our problem, we neither want to use any inbuilt function nor use any auxiliary space.

The basic idea is to run a for loop on the array and swap the array element at ith position with the array element at N-ith position.

This simply means, swapping the first element with the last element, the second element with the second last element, and so on until we reach the middle of the array.

Below is the implementation of the above algorithm:

// Reverse an array

const arr = [1, 2, 3, 4, 5, 6, 7];

let N = arr.length - 1;

for(let i=0; i <= Math.floor(N/2); i++){
    
    // Swap arr[i] with arr[N-i]
    let temp = arr[i];
    arr[i]   = arr[N-i];
    arr[N-i] = temp;
}

console.log(arr);
// Output: [7, 6, 5, 4, 3, 2, 1]

In case you want to swap the ith and N-ith element without using any temporary variable, you could use the array destructuring syntax.

Let’s say we have two variables a and b and we want to swap them using the destructuring syntax. This is how you can do it:

// Swap a and b
[a, b] = [b, a]

We can use this concept to swap the ith array element with N-ith element of the array.

Here is the updated code but with the array destructuring syntax:

// Reverse an array

const arr = [1, 2, 3, 4, 5, 6, 7];

let N = arr.length - 1;

for(let i=0; i <= Math.floor(N/2); i++){
    
    // Swap arr[i] with arr[N-i]
    [ arr[i], arr[N-i] ] = [ arr[N-i], arr[i] ];
    
}

console.log(arr);
// Output: [7, 6, 5, 4, 3, 2, 1]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts