Math.max() behaviour

aug 7 , 2013

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


array ruse

july 18 , 2013
[,,,].join() // ==> ",,"

wtf?

@eliranmal

Turns out that the trailing comma is removed (trailing commas are allowed in javascript, but not JSON). Once removed, there are only three "elements" in the array, and both are undefined. When join is called, by default it uses a comma, yielding ",,". I think this is what happens

@DDTrejo

JSON has nothing to do with this issue. Although trailing comma is really allowed by Javascript and that's the case. So [1,2,3,] equals to [1,2,3]. So literally [,,,] is something like [undefined, undefined, undefined,]. You can add undefined to the end explicitly to get 4 elements array:

[,,,undefined].join() // ==> ',,,'

@ixti


negative indexes

june 20 , 2013

Negative numbers mean different things to different functions on the Array prototype.


    var nums = [1, 2, 3];
    nums.splice(nums.indexOf('wtf'), 1);
    nums; // [1, 2]

@markdalgleish


isfinite null is true

apr 28 , 2013

isFinite function of JavaScript tests whether a number is finite.


    isFinite(42); // true
    isFinite(1/0); // false
    isFinite(0/0); // NaN is not finite -> false
    isFinite('42'); // true
    isFinite('hi'); // false

These are normal results.

    isFinite(); // false
    isFinite(undefined); // false

Undefined values are not finite. These are normal results too.

    isFinite(null); // true

Wait, what? Is null a number? It is converted into 0? Why?

Since null != 0 and null == undefined, (even thought null !== undefined) I expected null will behave something like undefined!

@123jimin


Fork me on GitHub