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? 
It is a check for NaN (as correctly pointed out in @Jonathan's comment). From the excellent Mozilla documentation:
NaNcompares unequal (via ==, !=, ===, and !==) to any other value -- including to anotherNaNvalue. UseNumber.isNaN()orisNaN()to most clearly determine whether a value isNaN. Or perform a self-comparison:NaN, and onlyNaN, will compare unequal to itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With