Skip to content

Find max value in Array JavaScript | Example code

  • by

The built-in functions Math.min() find the maximum value of the given Array in JavaScript. But These functions will not work as-is with arrays of numbers.

Math.max(5, 1, 6, 4); // 6

Function.prototype.apply() allows you to call a function with a given value and an array of arguments.

var numbers = [5, 1, 6, 4];
Math.max.apply(null, numbers) // 6

Find max value in Array JavaScript Example code

HTML complete code:-

Passing the numbers array as the second argument of apply() results in the function being called with all values in the array as parameters.

<!DOCTYPE html> 
<html> 

<body> 
	<script> 
		var numbers = [70, 20, 30, 90,50];
		var max = Math.max.apply(null, numbers); 

		console.log(max);
	</script> 
</body> 

</html> 

Output:

Find max value in Array JavaScript

Using spread operator

<script> 
		var numbers = [70, 20, 30, 90,50];
		var max = Math.max.apply(...numbers); 

		console.log(max);
</script> 

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