javascript / jquery - select the larger of two numbers

mheavers picture mheavers · Nov 16, 2012 · Viewed 21.4k times · Source

I'm trying to use javascript to select the greater of two numbers. I know I can write an if statement, but I'm wondering if there's some sort of Math operation or something to make this more efficient. Here's how I'd do it with an if statement:

if (a > b) {
    c = a;
}  
else {
    c = b;
}

Answer

BLSully picture BLSully · Nov 16, 2012

You're looking for the Max function I think....

var c = Math.max(a, b);

This function will take more than two parameters as well:

console.log(Math.max(4,76,92,3,4,12,9));
//outputs 92

If you have a array of arbitrary length to run through max, you can use apply...

var arrayOfNumbers = [4,76,92,3,4,12,9];
console.log(Math.max.apply(null, arrayOfNumbers));
//outputs 92

OR if you're using ES2015+ you can use spread syntax:

var arrayOfNumbers = [4,76,92,3,4,12,9];
console.log(Math.max(...arrayOfNumbers);
//outputs 92