JavaScript - Math.max() method

revision:


Math.max() method

The Math.max() static method returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters.

You can find the largest number (in a list of numbers) using the Math.max() method.

Syntax :

        Math.max()
        Math.max(value0)
        Math.max(value0, value1)
        Math.max(value0, value1, /* … ,*/ valueN)
    

Parameters

value1, value2, … , valueN : zero or more numbers among which the largest value will be selected and returned.

Examples

            Math.max(10, 20); // 20
            Math.max(-10, -20); // -10
            Math.max(-10, 20); // 20
        
            const arr = [1, 2, 3];
            const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
        

Since JavaScript "arrays" do not have a max() method, you can apply the Math.max() method instead.


Practical examples

example: returns the highest number in a list of number arguments.
code:
                    <div class="spec">
                        <a id="math"></a>
                    </div>
                    <script>
                            document.getElementById("math").innerHTML = Math.max(1,2,3, 5, 6, 12); 
                    </script>
                

example: return the highest number in a list of number arguments.

code:
                    <div class="spec">
                        <a id="math1"></a><br> 
                    </div>
                    <script>
                    document.getElementById("math1").innerHTML = Math.max.apply(null, [1,2,3, 5, 6, 12]); 
                    </script>
                

example: return the highest number in a list of number arguments.
code:
                    <div class="spec">
                        <a style="margin-left: 2vw;" id="math2"></a>          
                    </div>
                    <script>
                        document.getElementById("math2").innerHTML = Math.max.apply(" ", [1,2,3, 5, 6]); 
                    </script>