Skip to content

Find the largest number in array JavaScript | Example code

  • by

You can use for loop or reduce() method to get the largest number in array JavaScript. But the simplest way is Math.max() function.

3 Ways to find the largest number in array JS:

  • Math.max()
  • reduce() method
  • FOR loop

Find the largest number in array JavaScript Example

Let’s see one by every method in HMTL code:

Math.max()

Some ES6 magic for you, using the spread syntax.

<!DOCTYPE html>
<html>
<body>
	
	<script>

		var arr = [1, 5, 4, 9, 8];
		console.log(Math.max(...arr));  
	</script>

</body>
</html>

reduce() method

<script>

	var arr = [1, 5, 4, 9, 8];
	console.log(arr.reduce((element,max) => element > max ? element : max, 0));  
</script>

FOR loop

Let’s create a function for it:-

Create an array with the name of max then initialize max as the first element, then traverse the given array from the second element till the end. For every traversed element, compare it with max, if it is greater than max, then update max.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		function largest(arr) {  

        let max = arr[0]; 

        for (let i = 1; i < arr.length; i++) {
        	if (arr[i] > max) 
        		max = arr[i]; 
        } 
        return max; 
    } 

    let arr = [1, 5, 4, 9, 8];
    console.log(largest(arr));  
</script>

</body>
</html>

Output: Largest number will be the same for all examples because of Array values are the same.

Find the largest number in array JavaScript

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

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