0
0
JavascriptHow-ToBeginner · 3 min read

How to Reverse Array in JavaScript: Simple Guide

To reverse an array in JavaScript, use the reverse() method which reverses the elements in place. For example, array.reverse() changes the original array order to the opposite.
📐

Syntax

The reverse() method is called on an array and reverses its elements in place, returning the same array but with elements in reverse order.

  • array.reverse(): Reverses the array elements.
javascript
array.reverse()
💻

Example

This example shows how to reverse an array of numbers using reverse(). The original array is changed after calling the method.

javascript
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers);
Output
[5, 4, 3, 2, 1]
⚠️

Common Pitfalls

A common mistake is expecting reverse() to return a new reversed array without changing the original. It actually reverses the original array in place.

If you want to keep the original array unchanged, create a copy first using slice() or spread syntax.

javascript
const original = [1, 2, 3];
const reversedWrong = original.reverse();
console.log(original); // [3, 2, 1] - original changed

// Correct way to keep original unchanged
const original2 = [1, 2, 3];
const reversedCopy = [...original2].reverse();
console.log(original2); // [1, 2, 3] - original unchanged
console.log(reversedCopy); // [3, 2, 1]
Output
[3, 2, 1] [1, 2, 3] [3, 2, 1]
📊

Quick Reference

Remember these tips when reversing arrays in JavaScript:

  • reverse() changes the original array.
  • Use [...array] or array.slice() to copy before reversing if needed.
  • Works on arrays of any type (numbers, strings, objects).

Key Takeaways

Use array.reverse() to reverse an array in place in JavaScript.
reverse() modifies the original array, not a copy.
Create a copy with [...array] or slice() before reversing to keep the original unchanged.
The method works on arrays containing any data type.
Always check if you want to mutate the original array before using reverse().