JavaScript Array reverse() method


The reverse() method in JavaScript is used to reverse the order of the elements in an array. This method modifies the original array and returns a reference to the same array, now in reversed order.

Syntax:

array.reverse();

Return Value:

  • The reversed array. The original array is modified in place.

Key Points:

  • In-place operation: The reverse() method alters the original array, rather than creating a new one.
  • Works with any data type: The method can reverse arrays containing any type of data, including numbers, strings, objects, or even nested arrays.
  • Effect on empty arrays: Calling reverse() on an empty array will still return an empty array.

Example 1: Basic usage

let numbers = [1, 2, 3, 4, 5]; numbers.reverse(); // Reverse the order of elements console.log(numbers); // [5, 4, 3, 2, 1]

Example 2: Reversing an array of strings

let fruits = ['apple', 'banana', 'cherry']; fruits.reverse(); // Reverse the order of elements console.log(fruits); // ['cherry', 'banana', 'apple']

Example 3: Reversing an empty array

let emptyArray = []; emptyArray.reverse(); // Reverse an empty array console.log(emptyArray); // []

Example 4: Reversing a nested array

let nestedArray = [[1, 2], [3, 4], [5, 6]]; nestedArray.reverse(); // Reverse the order of nested arrays console.log(nestedArray); // [[5, 6], [3, 4], [1, 2]]

Example 5: Reversing and chaining methods

You can chain the reverse() method with other array methods:

let numbers = [1, 2, 3, 4, 5]; let reversedAndSorted = numbers.reverse().sort(); // Reverse and then sort console.log(reversedAndSorted); // [5, 4, 3, 2, 1] (sorted since reverse modifies the original array)

Summary:

  • The reverse() method is a simple and efficient way to reverse the order of elements in an array in JavaScript.
  • It modifies the original array and is useful for various applications, such as reversing the order of a list or preparing data for specific outputs.
  • Because it operates in place, be cautious if you need to maintain the original order of the array for later use.