Reverse an Array in JavaScript

In this tutorial, we'll take a look at how to reverse an array in JavaScript. There are a few ways to do this, and figuring out which one you'll want to employ typically depends on your personal preference.

We'll be reversing these two arrays:

let numArr = [1, 2, 3, 4, 5]
let strArr = ['Java', 'Python', 'JavaScript']

Using Array.reverse()

The easiest and simplest way to reverse an array is via the reverse() method:

let numArrReversed = numArr.reverse();
let strArrReversed = strArr.reverse();

console.log(numArrReversed);
console.log(strArrReversed);

We've created two new variables to point to the resulting arrays:

[ 5, 4, 3, 2, 1 ]
[ 'JavaScript', 'Python', 'Java' ]

Note: The reverse() method reverses the array in-place. This means that the original num_array and string_array are reversed and the original sequence is lost.

You don't need to create a new variable to store a pointer to these arrays in memory, since the original pointers already point to the reversed arrays:

numArr.reverse();
strArr.reverse();

console.log(numArr);
console.log(strArr);

This also results in:

[ 5, 4, 3, 2, 1 ]
[ 'JavaScript', 'Python', 'Java' ]

However, it's still common practice to "assign" the result to a new variable to indicate a changed state, or to at least assign a more indicative name to the transformed array, such as array_reversed.

Reversing an Array Functionally

Functional programming is a wonderful addition to most imperative programming languages. Functional constructs allow us to perform various, even complex, transformative operations on objects and sequences with intuitive and simple instructions.

Many developers simply love using functional constructs when they can, so it's no surprise that reversing an array is commonly done via functional constructs as well. This approach allows you to also pipe in another transformation alongside reversal, such as adding or changing the elements as well.

To reverse a array functionally in JavaScript, we'll leverage the spread operator and the map() function:

// Preserves original array
let numArrReversed = numArr.map(numArr.pop, [...numArr]);

// Doesn't preserve original array
let strArrReversed = [...strArr].map(strArr.pop, strArr);

The map() method maps each popped element (removed last element) from the numArr and pushes it into a new array, which is created as a copy of numArr. By removing the last element and adding it as the first into a new array, we create a new reversed array.

The first approach deals with a frozen copy of the numArr object, and thus doesn't modify the original array.

In the second approach, we modify the original array as we're using the reference to the original array in the map() method, even though we create a copy of the array beforehand:

console.log('Original num_array: ' + numArr);
console.log('Original string_array: ' + strArr);

console.log('Reversed num_array: ' + numArrReversed);
console.log('Reversed string_array: ' + strArrReversed);

Thus, when all is said and done, the num_array remains unchanged, while string_array is gone:

Original num_array: 1,2,3,4,5
Original string_array: 
Reversed num_array: 5,4,3,2,1
Reversed string_array: JavaScript,Python,Java

Reversing an Array with a for Loop

Finally, the good old way is to simply run the array through a for loop in backwards order, and add each element into a new array.

This works great for creating a new reversed array, but won't reverse the old one in-place. If you'd like to reverse it in-place, you'll want to use the unshift() method to add elements at the start of the array, while splicing (in-place operation) continually:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

function reverse(array) {
  let newArr = [];
  for(i = array.length-1; i >= 0; i--) {
    newArr.push(array[i]);
  }
  return newArr;
}

function reverseInPlace(array) {
  for(i = 0; i < array.length; i++) {
    let tmp = array.splice(i, 1)[0];
    array.unshift(tmp);
  }
  return array;
}

You can use these methods as:

let numArrReversed = reverseInPlace(numArr);
let strArrReversed = reverse(strArr);

console.log('Original num_array: ' + numArr);
console.log('Original string_array: ' + strArr);

console.log('Reversed num_array: ' + numArrReversed);
console.log('Reversed string_array: ' + strArrReversed);

Which results in:

Original num_array: 5,4,3,2,1
Original string_array: Java,Python,JavaScript
Reversed num_array: 5,4,3,2,1
Reversed string_array: JavaScript,Python,Java
Last Updated: March 7th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms