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]
And we want to reverse it to be like this
[5, 4, 3, 2, 1]
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);
Output
[ 5, 4, 3, 2, 1 ]
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
- 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);
Output
[ 5, 4, 3, 2, 1 ]
Thank you for reading
Thank you for reading my blog, you can read more awesome articles from my blog
Top comments (7)
Hey, it was a nice read, you got my follow, keep writing!
Thank you so much
What is performance complexity of each solution?
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:
My results:
Thanks for sharing
But why? Does Array.reverse have bad performance compared to your custom solution?
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