reverse() in JS – How to Reverse a JavaScript Array
Whenever you use reverse() on an array, the method does the following:
- It reverses the array so that its first item becomes the last and its last element becomes the first.
- It returns a reference to the reversed-original array.
Syntax of the reverse()
Method
reverse()
accepts no argument. Here is the syntax:
Examples
Below are examples of the reverse()
method.
How to reverse an array of three items
The snippet above used reverse()
to reorder numbersArray
’s elements so that its first item (1
) becomes the last and its last element (3
) becomes the first.
How to reverse an array of five items
The snippet above used reverse()
to reverse colorsArray
’s layout.
Important Stuff to Know about the reverse()
Method
Here are two essential facts to remember when using the reverse()
method.
1. reverse()
does shallow copy
reverse()
returns a shallow copy of the original array. In other words, reverse()
creates a reference between the returned array and its original.
Therefore, changes to the returned array will also reflect in the original.
Here’s an example:
You can see that mutating the reversedArray
also changed the original array because reverse()
returned a shallow copy of numbersArray
.
2. reverse()
reverses empty slots
reverse()
treats empty array slots like other filled indices.
Here’s an example:
You can see that reverse()
reversed the empty slot’s position like other filled indices.