Home » JavaScript

Array reverse() method with example in JavaScript

JavaScript reverse() method: Here, we are going to learn about the reverse() method of array in JavaScript.
Submitted by IncludeHelp, on February 28, 2019

JavaScript reverse() method

reverse() method is used to reverse the order of the elements in an array, it changes the actual array and also returns an array with reversed elements.

Syntax:

    array_name.reverse();

Parameters: None

Return value: Array with reversed elements.

Example:

    Input:
    var arr1 = [10, 20, 30, 40, 50];

    Function call:
    arr1.reverse();
    
    Output:
    50,40,30,20,10

JavaScript Code to demonstrate example of Array.reverse() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = ["Amit", "Ankur", "Akash"];
		
		//printing arrays before the reversing elements
		document.write("arr1: " + arr1 + "<br>");
		document.write("arr1 length: " + arr1.length + "<br>");
		document.write("arr2: " + arr2 + "<br>");
		document.write("arr2 length: " + arr2.length + "<br>");
		
		//reversing arrays
		arr1.reverse();
		arr2.reverse();
		
		//printing
		document.write("<br>After reversing ...<br><br>");
		document.write("arr1: " + arr1 + "<br>");
		document.write("arr2: " + arr2 + "<br>");
		
	</script>
</body>
</html>

Output

arr1: 10,20,30,40,50
arr1 length: 5
arr2: Amit,Ankur,Akash
arr2 length: 3

After reversing ...

arr1: 50,40,30,20,10
arr2: Akash,Ankur,Amit




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.