Skip to content

JavaScript max of array | Simple example code

  • by

JavaScript Math class offers max() functions which return the largest the given numbers respectively. We can use them to find the maximum in a JS array:

You have to use other method with max() to get max value element from array:-

  • reduce()
  • apply()
  • Spread Operator

JavaScript max of array Code

HTML Example code:

Use reduce()

The recommended approach is to use Array.reduce() to find the maximum element in an array. It does compare each value of the array:

<!DOCTYPE html> 
<html> 

<body> 
	<script> 
		const max = arr => arr.reduce((x, y) => Math.max(x, y));

		var arr = [ 16, 23, 35, 42, 59 ];
		console.log("Max:", max(arr));

	</script> 
</body> 

</html> 

Use apply()

Use the Function.prototype.apply() method for finding the maximum and minimum value in a numeric array.

<script> 
		var arr = [ 16, 23, 35, 42, 59 ];
		console.log("Max:", Math.max.apply(null, arr));

</script> 

Spread Operator (…)

Use the spread operator (...) which offers the shorter syntax of writing the apply method discussed above.

<script> 

		var arr = [ 16, 23, 35, 42, 59 ];
		console.log("Max:", Math.max(...arr));

</script> 

Output: Result will be same of all above example because of same array.

JavaScript max of array

Do comment if you have any doubts and suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading