How to Reverse an Array in JavaScript
Nov 30, 2021
To reverse an array in JavaScript, use the reverse()
function.
reverse()
will mutate the original array so be mindful of this fact when using this function.
const array = [1, 2, 3, 4, 5];
array.reverse();
array; // [5,4,3,2,1]
Immutable Approach
You can use the reverse()
function in combination with the slice()
function or spread operator ...
to prevent mutating the original array.
const array = [1, 2, 3, 4, 5];
const newArray = array.slice().reverse();
array; // [1,2,3,4,5]
newArray; // [5,4,3,2,1]
or
const array = [1,2,3,4,5];
const newArray = [...array].reverse();
array; // [1,2,3,4,5]
newArray; // [5,4,3,2,1]
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard