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:
arr.reverse();

// 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

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    MooTools 1.2 OpenLinks Plugin

    I often incorporate tools into my customers' websites that allow them to have some control over the content on their website. When doing so, I offer some tips to my clients to help them keep their website in good shape. One of the tips...

  • By
    Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

Discussion

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