Kodeclik Blog
Javascript’s Math.max() function
We will write a simple Javascript page to explore the Math.max() function. Given one or more numbers as inputs, Math.max() is a Javascript function that returns the largest input or NaN if any one of the inputs is not a number. Begin with a basic webpage:
In the above HTML page you see the basic elements of the page like the head element containing the title (“Javascript Math.max() function”) and a body with an empty script tag. The Javascript code goes inside these tags.
Using Math.max() in Javascript
Here is some simple code to compute the maximum of a set of numbers.
The output is:
In general you can provide a more elaborate range of numbers:
The output is, as expected:
Math.max() with no parameters passed
If we do not pass any arguments to Math.max(), like so:
The output is:
Note that Math.max() returns “-Infinity” if no arguments are given.
Math.max() with non-numeric arguments
If we use non-numeric arguments with Math.max() like so:
we will get the output:
Note that Math.max() returns NaN if at least one of its inputs is not numeric.
Math.max() with an array
Let us try to find the maximum value in an integer array. Here is an attempt:
The output is:
Wow - what happened? Note that Math.max() takes individual numbers as input whereas you are passing an array. You should use spread notation to achieve your goal:
The output is, as expected:
Would you like to learn more Javascript? Checkout our blog post on how you can use Javascript’s Array shift() method.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.