What does reverse() do?
The reverse() method in JavaScript reverses the order of the array's elements,
meaning the first becomes the last, and the last becomes the first.
Example:
javascript
const arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // [4, 3, 2, 1]- Elements are rearranged in place (in the original array).
- The method mutates the array.
- Returns the same modified array (convenient for chaining).
Behavior:
| Property | Description |
|---|---|
| Changes element order | Yes |
| Modifies the original array | Yes |
| Returns | The same array (now reversed) |
| Return value type | Array |
Example with text:
javascript
const letters = ["a", "b", "c"];
const reversed = letters.reverse();
console.log(reversed); // ["c", "b", "a"]
console.log(letters); // ["c", "b", "a"] - the same object!letters and reversed are the same array,
because reverse() returns a reference to the original object.
If you want to keep the original
If you need to reverse without changing the original array, make a copy first:
javascript
const arr = [1, 2, 3];
const reversed = [...arr].reverse();
console.log(arr); // [1, 2, 3]
console.log(reversed); // [3, 2, 1]Can also be used with strings:
Strings do not have a reverse() method,
but you can achieve it via an array of characters:
javascript
const str = "hello";
const reversed = str.split("").reverse().join("");
console.log(reversed); // "olleh"Summary:
| What it does | Reverses the order of elements |
|---|---|
| Mutates the array | Yes |
| Returns | The modified array |
| Safe version | [...arr].reverse() |
| Example | [1,2,3].reverse() -> [3,2,1] |
In short:
reverse()rearranges the array's elements in reverse order, modifying the original array.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.