views:

1047

answers:

2

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?

+16  A: 

Use max twice:

max(num1, max(num2, num3))

Eric J.
+1 Got to love the beauty of simplicity.
Kyle Rozendo
Math.max can accept any arbitrary number of arguments, see my answer below: http://stackoverflow.com/questions/1418569/javascript-max-function-for-3-numbers/1418646#1418646
CMS
@CMS: +1 Very cool, I learned something. I'm not aware of another mainstream language that does that, though in principal any language that can accept a variable number of function arguments could.
Eric J.
+16  A: 

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
CMS
+1 I don't know why this hasn't been picked up on before and it's by far the simplest solution. If you want it to work with an array just use Math.max.apply(Math, array)
sighohwell
Google seems to love SO. I was googling 'javascript max' 45 minutes after the question was first posted, and found this answer on the first page :-)
Eric J.