Perplexing if condition in jQuery merge function

292 views Asked by At

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?

2

There are 2 answers

2
Andbdrew On BEST ANSWER

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.

6
Nathan Wilson On

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.