Fraser Hamilton

How to reverse an array in JavaScript

June 16, 2020

Reversing an array in JavaScript couldn’t be any easier thanks to Array.prototype.reverse() method. You can use it on any array like this:

const cities = ['paris', 'london', 'new york', 'rome']

const reversed = cities.reverse()

console.log(reversed)

// ['rome', 'new york', 'london', 'paris']

This method reversing the array using an in place method.

What if we wanted to reverse the array without using this method? Well we could create our own function that does it for us.

const reverseArray = arr => {
  let rev = new Array()
  for (let i = arr.length - 1; i >= 0; i--) {
    rev.push(arr[i])
  }
  return rev
}

const cities = ['paris', 'london', 'new york', 'rome']

const reversed = reverseArray(cities)

console.log(reversed)

// ['rome', 'new york', 'london', 'paris']


Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton