Quick Way to Reverse an Array in JavaScript


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

To reverse the order of items of an array without modifying the original array we can use the reverse() method and the unshift() method in JavaScript.

With this methods you can reverse an array without any external library in JavaScript.

Reverse an Array with reverse() method.

The reverse() method reverse the order of the items in an array in JavaScript. It does not modify the original array and return us a new array.

Syntax:

array.reverse()

Example:

const array = [1,2,3,4]
const reverseArr = array.reverse()
console.log(reverseArr)

// output : [ 4, 3, 2, 1 ]

Using Unshift() method

The unshift() method adds elements to the beginning of an array in JavaScript and return us the new length of the array.

Syntax:

Array.unshift(item1, item2,...)

Here to reverse the elements in an array we will use forEach() along with unshift() method to get the result.

Let's see it in action:

array = [1, 2, 3, 4];
reverseArr = [];
array.forEach(element => {
    reverseArr.unshift(element)
});
console.log(reverseArr);
//output : [ 4, 3, 2, 1 ]

Here, we have loop through each elements of the array using forEach() and then using the unshift() method each element are placed at the beginning of the empty array (reverseArr) one by one.

Related Topics:

Remove First And Last Element From An Array In JavaScript

How To Sort An Array Alphabetically In Javascript?

How To Remove A Specific Item From An Array In JavaScript ?

How To Copy Or Clone An Array In JavaScript

Loop An Array In JavaScript | Quick Ways

How To Empty An Array in JavaScript?


💾 Recommended Articles