JavaScript: Reverse Arrays


Manipulating knowledge is core to any programming language. JavaScript isn’t any exception, particularly as JSON has token over as a primary knowledge supply format. One such knowledge manipulation is reversing arrays. You could need to reverse an array to indicate most up-to-date transactions, or easy alphabetic sorting.

Reversing arrays with JavaScript initially was completed through reverse however that might mutate the unique array:

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

// Reverse it with out reassigning:
arr.reverse();

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

Modifying the unique array is a legacy methodology. To keep away from this mutation, we would copy the array after which reverse it:

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

Nowadays we are able to use toReversed to keep away from mutating the unique array:

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

Avoiding mutation of knowledge objects is extremely essential in a programming language like JavaScript the place object references are significant.

  • 39 Shirts – Leaving Mozilla

    In 2001 I had simply graduated from a small city highschool and headed off to a small city school. I discovered myself within the quaint laptop lab the place the substandard computer systems featured two browsers: Web Explorer and Mozilla. It was this lab the place I fell…

  • Designing for Simplicity

    Earlier than we get began, it is price me spending a short second introducing myself to you. My identify is Mark (or @integralist if Twitter occurs to be your communication instrument of selection) and I at present work for BBC Information in London England as a principal engineer/tech…


Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles