Ben Shelock Ben Shelock -4 years ago 129
Javascript Question

Javascript max() function for 3 numbers

I need to find the highest number from 3 different numbers. The only thing I've found is max() but you can only use 2 numbers.

Whats the best way?

Answer Source

The Math.max function can accept any arbitrary number of arguments:

Syntax:

Math.max([value1[,value2[, ...]]]) 

Usage:

var max = Math.max(num1, num2, num3);

For example:

alert(Math.max(1,2,3,4,5,6)); // alerts 6

You could even use it to get the maximum value of an array of numbers as @Pascal MARTIN suggest, with the help of apply:

Array.prototype.max = function () {
    return Math.max.apply(Math, this);
};


var max = [1,2,3,4,5,6].max(); // 6
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download