views:

77

answers:

4
var one = 1415;
var two = 2343;
var three = 11;

How to get the biggest number from these variables? (the shortest way wanted)

+5  A: 

Math.max(one, two, three)

shabunc
@WorkingHard, you can use either Math.max.apply(null,[3,2,1]) or sort array (by desc) and take the first element - [1,4,3,2].sort(function(a,b){return a<b?1:a>b?-1:0})[0]
shabunc
+1  A: 

Put them in an array, sort them, and take the last of the sorted values:

[one, two, three].sort(function (a, b) {
  return a > b ? 1 : (a < b ? -1 : 0);
}).slice(-1);
Todd Yandell
Todd, actually, there's no any guarantee, that array will be sorted numerically. You should sort this way - [n1,n2,n3].sort(function(a,b){return a>b?1:a<b?-1:0})
shabunc
Interesting, I didn’t realize that. It sorts each item based on its string representation, so 30 comes before 4.
Todd Yandell
+2  A: 

If you have them in an array, you can do this:

var numbers_array = [1415, 2343, 11];

numbers_array.push( 432 ); // now the array is [1415, 2343, 11, 432]

var biggest = Math.max.apply( null, numbers_array );
RightSaidFred
@WorkingHard - You use `.push()` to add items to the top of an array. I'll give an example in my answer.
RightSaidFred
A: 
function biggestNumber(){
    return Math.max.apply(this,arguments);
}

var one= 1415;
var two= 2343;
var three= 11;

biggestNumber(one, two, three)

/* returned value: (Number) 2343 */

kennebec
Why wouldn't you just call `Math.max` regularly in that case?
CD Sanchez