Skip to content
the poor coder

Reverse an array java script

Poor Man
Published
Reading time
1 min read
On this page

Reverse an Array in JavaScript#

The Problem#

You have an array in JavaScript and you need to reverse the order of its elements.

The Solution#

The easiest way to reverse an array in JavaScript is to use the built-in reverse() method. This method reverses the order of the elements in place and returns the reversed array.

Text

let arr = [1, 2, 3, 4, 5];
arr.reverse(); // [5, 4, 3, 2, 1]

If you don't want to modify the original array, you can create a copy of it and reverse the copy using slice() and reverse():

Text

let arr = [1, 2, 3, 4, 5];
let reversedArr = arr.slice().reverse(); // [5, 4, 3, 2, 1]

You can also reverse an array using a loop:

Text

let arr = [1, 2, 3, 4, 5];
let reversedArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
  reversedArr.push(arr[i]);
}
// [5, 4, 3, 2, 1]

Explanation#

JavaScript's reverse() method reverses the order of the elements in an array in place. This means that it modifies the original array and returns a reference to the same array.

The slice() method creates a shallow copy of an array. This means that it creates a new array with the same elements as the original array. If you pass no arguments to slice(), it will copy the entire array. If you pass arguments, it will copy the elements between the specified indexes.

The loop solution works by iterating over the original array in reverse order and pushing each element onto a new array.

Conclusion#

Reversing an array in JavaScript is easy using the reverse() method or a loop. If you need to reverse an array without modifying the original, you can create a copy of it using slice().

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC