Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perplexing if condition in jQuery merge function

I was just going through the code of jQuery and came across the function merge. I checked out the code of this function:

merge: function( first, second ) {
    var len = +second.length,
        j = 0,
        i = first.length;

    while ( j < len ) {
        first[ i++ ] = second[ j++ ];
    }

    // Support: IE<9
    // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)

    if ( len !== len ) {
        while ( second[j] !== undefined ) {
            first[ i++ ] = second[ j++ ];
        }
    }

    first.length = i;

    return first;
},

Now if you go through the code, you will come across the following if check:

if ( len !== len )

This somehow doesn't make sense to me, what exactly is this check for, and what is it doing ?

len is clearly defined a few lines above, like so:

var len = +second.length;

So why would someone check if len !== len? This somehow doesn't make sense to me. Can somebody explain?

like image 507
Tenali_raman Avatar asked Jun 21 '15 19:06

Tenali_raman


2 Answers

It is a check for NaN (as correctly pointed out in @Jonathan's comment). From the excellent Mozilla documentation:

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

like image 86
Andbdrew Avatar answered Oct 10 '22 21:10

Andbdrew


The + operator (unary plus) in the assignment var len = +second.length; tries to convert the value second.length into a number by internally calling valueOf() and toString(). If the conversion to a number fails, it will assign NaN to the variable len. As previously stated, len !== len is a way to check for NaN.

like image 4
Nathan Wilson Avatar answered Oct 10 '22 22:10

Nathan Wilson