DEV Community

Mohamed Ibrahim
Mohamed Ibrahim

Posted on • Updated on • Originally published at mo-ibra.com

How to reverse an array in JavaScript

In this article we will learn how to reverse an array in JavaScript.

There's more than one way to do this:

  • Using reverse() method (Built In)
  • Using for loop

There are two ways, the first is easy because there's a built-in function in JavaScript that does this, and the second is to create that function with ourselves.

It is better for you in the production stage to use what is in the language, but in the learning stage it is better to understand what is happening behind the scenes.


Our Problem

Now what is our problem? The problem is that there's an array and we want to reverse it.

Imagine that there is a array like that:

[1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

And we want to reverse it to be like this

[5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

As we said earlier, we can solve the problem in two ways.

  • Using reverse() method (Built In)
  • Using for loop

Using reverse() method (Built In)

We can use reverse() method to solve our problem.

Example

// Array
let myArray = [1, 2, 3, 4, 5];

// Reverse the array
let reversedArr = myArray.reverse();

// Result:
console.log(reversedArr);
Enter fullscreen mode Exit fullscreen mode

Output

[ 5, 4, 3, 2, 1 ]
Enter fullscreen mode Exit fullscreen mode

Using for loop

Now, before writing the code, we must understand how we will solve this problem by for loop?

First, iteration using for iterate over every element in the array, right?

Well here it means that we can start from the last element in the array to the first element (the opposite)

Then we can add each element to a new array.

Summarize the solution as follows:

  • Iterate over every element in our array
  • Iteration will start from the last to the first
5, 4, 3, 2, 1
Enter fullscreen mode Exit fullscreen mode
  • Add each element to a new array.

Full code

// Array
let myArray = [1, 2, 3, 4, 5];

// Create new array
let result = [];

// Iterate over every element in our array
for (let i = myArray.length - 1; i >= 0; i--) {
    // Add every element to new array
    result.push(myArray[i]);
}

// Result:
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output

[ 5, 4, 3, 2, 1 ]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Thank you for reading my blog, you can read more awesome articles from my blog

Top comments (7)

Collapse
 
naucode profile image
Al - Naucode

Hey, it was a nice read, you got my follow, keep writing!

Collapse
 
moibra profile image
Mohamed Ibrahim

Thank you so much

Collapse
 
meatboy profile image
Meat Boy • Edited

What is performance complexity of each solution?

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Time complexity of both is O(n), but amazingly, it seems OP’s custom implementation is faster than the native one for large arrays, at least in Chrome. That's presumably because creating a new copy of the array is faster than mutating it.

Perf test:

const customReverse = (arr) => {
    let result = []

    for (let i = arr.length - 1; i >= 0; i--) {
        result.push(arr[i])
    }

    return result
}

for (const n of Array.from({ length: 7 }, (_, i) => 10 ** (i + 1))) {
    const arr1 = Array.from({ length: n }, (_, i) => i)
    const arr2 = Array.from({ length: n }, (_, i) => i)

    console.time(`native @ length ${n.toExponential()}`)
    const arr1Out = arr1.reverse()
    console.timeEnd(`native @ length ${n.toExponential()}`)

    console.time(`custom @ length ${n.toExponential()}`)
    const arr2Out = customReverse(arr2)
    console.timeEnd(`custom @ length ${n.toExponential()}`)

    // sanity check
    console.assert(arr1[0] === n - 1, 'arr1') // mutated
    console.assert(arr2[0] === 0, 'arr2') // left unchanged
    console.assert(arr1Out[0] === n - 1, 'arr1Out')
    console.assert(arr2Out[0] === n - 1, 'arr2Out')
}
Enter fullscreen mode Exit fullscreen mode

My results:

native @ length 1e+1: 0.007080078125 ms
custom @ length 1e+1: 0.0380859375 ms
native @ length 1e+2: 0.0068359375 ms
custom @ length 1e+2: 0.014892578125 ms
native @ length 1e+3: 0.0517578125 ms
custom @ length 1e+3: 0.049072265625 ms
native @ length 1e+4: 0.748779296875 ms
custom @ length 1e+4: 0.5439453125 ms
native @ length 1e+5: 5.950927734375 ms
custom @ length 1e+5: 1.090087890625 ms
native @ length 1e+6: 79.328125 ms
custom @ length 1e+6: 11.468994140625 ms
native @ length 1e+7: 826.280029296875 ms
custom @ length 1e+7: 170.901123046875 ms
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moibra profile image
Mohamed Ibrahim

Thanks for sharing

Collapse
 
brense profile image
Rense Bakker

But why? Does Array.reverse have bad performance compared to your custom solution?

Collapse
 
moibra profile image
Mohamed Ibrahim • Edited

In this lesson, I do not recommend using my custom solution, because the built-in function may perform better, but it is an explanation only for beginners who do not know how things are done behind the scenes, so I've written two solutions