JavaScript provides an array of methods to perform different operations on arrays. Among those methods, Array.reverse()
stands out for its simplicity and effectiveness in reversing arrays. However, as a JavaScript developer, you might also want to know how to reverse an array without mutating the original array. This article will explore both of these topics.
Array.reverse()
Using The Array.reverse()
method is the most straightforward way to reverse an array in JavaScript. This method mutates the original array by reversing the order of its elements in-place.
Here is an example:
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // Outputs: [5, 4, 3, 2, 1]
As you can see, the Array.reverse()
method is extremely simple to use. However, it's important to remember that this method changes the original array.
Array.toReversed()
Method
Introducing the In many cases, you may want to reverse an array without mutating the original array. JavaScript introduced Array.toReversed()
to do just that.
Here is how you can use it:
let arr = [1, 2, 3, 4, 5];
let reversedArr = arr.toReversed();
console.log(arr); // Outputs: [1, 2, 3, 4, 5]
console.log(reversedArr); // Outputs: [5, 4, 3, 2, 1]
You should always try and avoid mutating existing data objects wherever possible.
Interested in proving your knowledge of this topic? Take the JavaScript Fundamentals certification.
JavaScript Fundamentals
Showcase your knowledge of JavaScript in this exam, featuring questions on the language, syntax and features.
$99