Javascript Array - reverse() Method

Tutorialsrack 29/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.reverse(). How does this method work in javascript? 


The Array.prototype.reverse() method is used to reverse the elements of the given array.


This method takes no parameter. And this reverse() method overwrites the original array.

If you used this method on sparse arrays, sparse arrays remain sparse. Empty slots are copied over to their respective new indices as empty slots.

Here are some examples of Array.prototype.reverse() method:

//Example 1
//Reversing the elements in an array
console.log([1, 2, 3, 4, 5, 6].reverse());
// Output => [6, 5, 4, 3, 2, 1]

//Example 2
const languages = ["JavaScript", "Python", "C++", "Java", "Go"];

// reversing the order of languages array
const reversedArray = languages.reverse();

console.log("Reversed Array: ", reversedArray);
/* Output => 

"Reversed Array: "
["Go", "Java", "C++", "Python", "JavaScript"]


// modifies the original array
console.log("Original Array: ", languages);
/* Output => 

"Original Array: "
["Go", "Java", "C++", "Python", "JavaScript"]


//Example 3: Using reverse() on sparse arrays
console.log([1, , 3].reverse()); 
// Output => [3, empty, 1]

console.log([1, , 3, 4].reverse()); 
// Output => [4, 3, empty, 1]

I hope this article will help you to understand the javascript Array built-in method Array.prototype.reverse()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts