The reverse()
method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
Example 1: Reversing a simple array
// Example of reversing an array of numbers
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1]
Explanation
The reverse()
method is called on the numbers
array, and it reorders the elements in place from last to first.
Example 2: Reversing an array of strings
// Example of reversing an array of strings
const letters = ['a', 'b', 'c'];
letters.reverse();
console.log(letters); // Output: ['c', 'b', 'a']
Explanation
reverse()
works on arrays of any data type, including strings. The letters
array is modified to have its elements in the opposite order.
Example 3: Reversing an array with mixed data types
// Example of reversing an array with mixed data types
const mixedData = [1, 'two', { three: 3 }, [4, 5]];
mixedData.reverse();
console.log(mixedData); // Output: [[4, 5], { three: 3 }, 'two', 1]
Explanation
The order of all elements is reversed regardless of their data type. The nested array [4, 5]
becomes the first element.
Example 4: The return value of reverse()
// Example showing that reverse() returns the reversed array
const array1 = ['one', 'two', 'three'];
const reversedArray = array1.reverse();
console.log(array1); // Output: ['three', 'two', 'one']
console.log(reversedArray); // Output: ['three', 'two', 'one']
console.log(array1 === reversedArray); // Output: true
Explanation
The reverse()
method returns a reference to the same, now-reversed, array. It does not create a new array.
Example 5: Reversing a sorted array
// Example of sorting and then reversing an array
const scores = [78, 92, 85, 64];
scores.sort((a, b) => a - b).reverse(); // Sort ascending, then reverse
console.log(scores); // Output: [92, 85, 78, 64] (now sorted descending)
Explanation
Method chaining can be used here. First, sort()
arranges the numbers in ascending order. Then, reverse()
is called on the sorted array to get a descending order.
Example 6: Using reverse() to check for palindromes
// Example of using reverse() to check if a string is a palindrome
function isPalindrome(str) {
const reversedStr = str.split('').reverse().join('');
return str === reversedStr;
}
console.log(isPalindrome('madam')); // Output: true
console.log(isPalindrome('hello')); // Output: false
Explanation
Though we are checking a string, reverse()
is an array method. We first convert the string to an array of characters, reverse the array, and then join it back into a string to perform the comparison.
Example 7: Reversing an empty or single-element array
// Example of reversing an empty or single-element array
const empty = [];
const single = ['A'];
empty.reverse();
single.reverse();
console.log(empty); // Output: []
console.log(single); // Output: ['A']
Explanation
Calling reverse()
on an empty or single-element array has no effect, as there is no order to reverse.