Print A Maximum Number From An Array in JavaScript

Date Published: 27/03/2020 Published By: JaiSchool

This guide includes two ways of printing maximum numbers from an array in Javascript. First, we will learn how to print the max number using a predefined method Math.max(). And the second one is, using a loop.

This one is tricky but not that if you read code example line by line and understand.

Table of Contents
Print max number from array by Math.max()
Print max number from array by loop

This is simple. Use the array name in the argument of Math.max(). It will return the max number from the array so print it.

<!DOCTYPE html>
<html>
<head>
	<title>Print the maximum using Math.max() function in JS</title>
</head>
<body>

<script>
	var numbers = [8,20,76,47,89,68,31,93,3];
	
	var max_number = Math.max(...numbers);

	alert(max_number);

</script>
</body>
</html>

Know the mean of three dots in Javascript.

First of all, get the length of the array and then run a loop till the array length lasts. And then create a variable out of the for loop. Assign initial value 0 to define its data type internally.

Then in the for loop, use if condition. Here, in the below example if number[i]>max_number then the condition will execute and replace the value in the var max_number.

Again the code in the loop executes, condition checked and assigned a new value in max_number (if the condition becomes true).

It keeps going on as long as the length of an array.

<!DOCTYPE html>
<html>
<head>
	<title>Print the maximum number from an array</title>
</head>
<body>

<script>
	var numbers = [8,20,76,47,89,68,31,3];
	var length = numbers.length;
	var max_number = 0;
	var i;
	for(i=0;i<length;i++)
	{
		if(numbers[i]>max_number)
		{
		max_number = numbers[i];
		}
	}
	alert(max_number);
</script>
</body>
</html>
Some SQL Topics
A basic introduction to SQL
Create a database in Mysql using SQL
Delete a database in MySql using SQL
Create a table in MySql using SQL
Delete a table in MySql using SQL

Publish A Comment

Leave a Reply

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