JavaScript: Reverse Arrays

By  on  

Manipulating data is core to any programming language. JavaScript is no exception, especially as JSON has token over as a prime data delivery format. One such data manipulation is reversing arrays. You may want to reverse an array to show most recent transactions, or simple alphabetic sorting.

Reversing arrays with JavaScript originally was done via reverse but that would mutate the original array:

// First value:
const arr = ['hi', 'low', 'ahhh'];

// Reverse it without reassigning:

// Value:
arr (3) ['ahhh', 'low', 'hi']

Modifying the original array is a legacy methodology. To avoid this mutation, we'd copy the array and then reverse it:

const reversed = [...arr].reverse();

These days we can use toReversed to avoid mutating the original array:

const arr = ['hi', 'low', 'ahhh'];
const reversed = arr.toReversed(); // (3) ['ahhh', 'low', 'hi'];
arr; // ['hi', 'low', 'ahhh']

Avoiding mutation of data objects is incredibly important in a programming language like JavaScript where object references are meaningful.

Recent Features

Incredible Demos

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Introducing MooTools NextPrev

    One thing I love doing is duplicating OS functionalities. One of the things your OS allows you to do easily is move from one item to another. Most of the time you're simply trying to get to the next or the previous item.


    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!