Reverse an Array in JavaScript.

“In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.”

How to reverse an array in javascript ?

The reverse() method reverses the order of the elements in an array.

Array store in a single variable.

In the .reverse() method the arrays last element becomes first and the first element becomes the last. This method also made the changes in the original array.

Mutating Original Array.

Now if we don’t want to mutate our original array, so we can use this -

  1. .reverse() with .slice()
  2. .reverse() with .spread()
  3. .reduce() and .spread()
  4. .reduceRight() and .spread()

1 .reverse() with .slice()

The .slice() method returns the selected elements in an array, as a new array object.

The JavaScript array .reverse()method changes the sequence of elements of the given array and returns the reverse sequence.

Reverse an array with .slice()

2 .reverse() with .spread()

The spread syntax is simply three dots: ...

Spread syntax can perform all of the array manipulations that previously required push, concat, or slice methods.

Reverse an array with […spread] operator.

3 → .reduce() and .spread()

The .reduce() method reduces the array to a single value.

The .reduce() method executes a provided function for each value of the array (from left-to-right).

Note: this method does not change the original array.

More Details about .reduce() Method.
Reverse an array with .reduce() method.

4 → .reduceRight() and .spread()

The .reduceRight() method reduces the array to a single value.

The .reduceRight()method executes a provided function for each value of the array (from right-to-left).

Reverse an array with .reduceRight() method.

“Programmers are not to be measured by their ingenuity and their logic but by the completeness of their case analysis.”

You can check this link for more details.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store