Skip to content

JavaScript array max value | Simple example code

  • by

Use Math.max or for each loop to get the maximum element in JavaScript. You can use the Math.max() methods in combination with the apply() method to find the maximum values within an array.

JavaScript array max value Example

Let’s See HTML example code:

Using Math.max()

These functions could be passed an array with the spread(…) operator. The spread operator allows an iterable to expand in places where multiple arguments are expected.

<!DOCTYPE html> 
<html> 

<body> 
	<script> 
		
		var array = [40, 60, 50, 10, 40]; 
		
		var maxValue = Math.max(...array); 
		console.log(maxValue);
		
	</script> 
</body> 

</html> 

Iterating through the array (for Each)

Iterating through all the elements in the array and updating the maximum element until that point by comparing them to the current maximum values.

<!DOCTYPE html> 
<html> 

<body> 
	<script> 
		
		var array = [40, 60, 50, 10, 40]; 
		maxValue = -Infinity;

		for (item of array) {

			if (item > maxValue)
				maxValue = item;
		}
		console.log(maxValue);

	</script> 
</body> 

</html> 

Output:

JavaScript array max value

Do comment if you have any comment or suggestions on this JS Array.

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

Your email address will not be published. Required fields are marked *