created by Brian LeRoux & Andrew Lunny. sparodically uncurated by David Trejo.

2013 08 07 Math.max() behaviour

Math.max() has an interesting behaviour, handling different JavaScript data types in different ways.

    Math.max(3, 0);           // 3
    Math.max(3, {});          // NaN
    Math.max(3, []);          // 3
    Math.max(3, true);        // 3
    Math.max(3, 'foo');       // NaN
    Math.max(-1, null);       // 0
    Math.max(-1, undefined);  // NaN

Now, let's focus on Booleans:

    Math.max(1, true);     // 1
    Math.max(0, true);     // 1
    Math.max(1, false);    // 1
    Math.max(-1, true);    // 1
    Math.max(-1, false);   // 0

And now, on Arrays:

    Math.max(-1, []);      // 0
    Math.max(-1, [1]);     // 1
    Math.max(-1, [1, 4]);  // NaN

So next time, watch out for what you pass into Math.max().

@gnclmorais

Math.max() typecasts all values to Numbers (Number(x)), e.g.:

Math.max(false, -1); // 0
Math.max(5, "10");   // 10

@ixti

Fork me on GitHub