How to reverse an array in JavaScript

ยท

2 min read

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 ]

This is the first solution, and I do not recommend it at the learning stage, because it does not benefit you much.


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, and let's connect!

Thank you for reading my blog.๐Ÿš€ You can find more awesome article in my blog ๐Ÿš€

ย