How to Reverse an Array in JavaScript
Table of Contents
Arrays are a useful data structure in JavaScript because they contain a collection of elements where each one can be accessed by an index.
Sometimes it is useful for the same array to be in the reverse order.
In this article, we will look at how to reverse an array in JavaScript.
How to reverse an array
The easiest way to reverse an array is to use the built-in reverse method.
Let's start with an example array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
console.log(array);
BASH[1, 2, 3, 4, 5]
Now let's call the reverse
method on the array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array);
BASH[5, 4, 3, 2, 1]
Notice that this method directly mutates the array, so we don't need to assign the result to a new variable.
This can be good in the case that we don't want to create a new array, but it can also be bad if we want to keep the original array.
If you want to keep the original array, you'll have to make a copy of the array using the spread operator:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const reversedArray = [...array].reverse();
console.log(array);
console.log(reversedArray);
BASH[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Conclusion
In this article, we looked at how to reverse an array in JavaScript.
We saw that the easiest way to reverse an array is to use the built-in reverse method, but if you want to keep the original array, make a copy of it, then reverse the copy.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Using Puppeteer and Jest for End-to-End Testing
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API