Alexander Solonik
Alexander Solonik

Reputation: 10230

understanding javascripts ( length - 1 ) in obj check to test for isArraylike (jquery)

I was just going through the source code of jquery and came across the following function:

function isArraylike( obj ) {

    // Support: iOS 8.2 (not reproducible in simulator)
    // `in` check used to prevent JIT error (gh-2145)
    // hasOwn isn't used here due to false negatives
    // regarding Nodelist length in IE
    var length = "length" in obj && obj.length,
        type = jQuery.type( obj );

    if ( type === "function" || jQuery.isWindow( obj ) ) {
        return false;
    }

    if ( obj.nodeType === 1 && length ) {
        return true;
    }

    return type === "array" || length === 0 ||
        typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}

if you go line by line , you will see that jquerys internal methods get called such as $.type and $.isWindow, now the part I don't understand is right at the end, its the following piece of code:

( length - 1 ) in obj;

I see the && used in the end, my only question is when does this check return true and when does it return false? Its really hard to tell, is that check only for when obj is an object or also when obj is an array?

What is that check really really checking for?

I created the following piece of code, to make some sense of that line:

arr = ['hello' , 'world'];

check = (arr - 1) in arr;

console.log(check);

Well I get a false in the console, I have no idea what scenario would return a true . Can somebody shed some light on this please?

Upvotes: 1

Views: 278

Answers (1)

ikrabbe
ikrabbe

Reputation: 1929

This is very simple but has nothing to do with jquery. That's just javascript. It checks if a key is part of an object or array.

var a=["a","b","c","d"]

has at least four keys 0,1,2 and 3 so you can positively test all those keys, i.e. in the console

0 in a
true
1 in a
true
2 in a
true
3 in a
true
4 in a
false

So (length-1) in obj checks if the last element of the array or object is defined or not.

That is done, as you could define a as

var a={ "0":"a", "3":"d", "length":4 }

which would be a sparse array.

Your test code would be

arr = ['hello' , 'world'];
check = (arr.length - 1) in arr;
console.log(check);

Upvotes: 2

Related Questions