javascript / jquery - select the larger of two numbers

22,955

Solution 1

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

Solution 2

c = (a > b) ? a : b;

This will do the same thing. This can be really useful and a real time saver.

Share:
22,955
mheavers
Author by

mheavers

Updated on April 25, 2020

Comments

  • mheavers
    mheavers about 4 years

    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;
    }
    
  • James Gentes
    James Gentes over 4 years
    The parentheses can be omitted