Search code examples
javascriptfor-in-loop

Javascript for in


I came across an interview question as below but I could not figure out how javascript internals interprets the following code.

Can someone please explain how the JS engine is interpreting for in? Does that mean "in" is not a check for values being contained in an array?

const array = [1,2,3,4,5];

console.log(0 in array)


console.log("0" in array)


console.log(4 in [1,2,3,4,5])


console.log(4 in [1,2,3,4])


Solution

  • Can someone please explain how the JS engine is interpreting for in?

    None of those examples uses for-in, which looks like this:

    for (const key in something)
    

    They just use the in operator, which is something else entirely (though, perhaps, somewhat related).

    Two things come into play in that code:

    • The in operator checks to see if the property named on the left (the name is converted to string if needed) exists in the object on the right (on the object itself, or on any of its prototypes).
    • Arrays are objects. An array index is actually a property name.

    Picking up on that second point, let's look at the array [1,2,3,4,5]:

    +−−−−−−−−−−−−−−−+
    |    (array)    |
    +−−−−−−−−−−−−−−−+
    | "length":   5 | Property name is "length", value is 5
    | "0":        1 | Property name is "0", value is 1
    | "1":        2 |
    | "2":        3 |
    | "3":        4 |
    | "4":        5 |
    | [[Prototype]] |−−−−>Array.prototype, which has various methods
    +−−−−−−−−−−−−−−−+
    

    Based on that information:

    const array = [1,2,3,4,5];
    console.log(0 in array);
    

    in converts 0 to "0" and checks for a property with that name on array. There is one, so the result is true.

    const array = [1,2,3,4,5];
    console.log("0" in array);
    

    in checks for a property called "0" property on array. There is one, so the result is true.

    console.log(4 in [1,2,3,4,5]);
    

    in converts 4 to "4" and checks for a property with that name on [1,2,3,4,5]. There is one, so the result is true.

    console.log(4 in [1,2,3,4]);
    

    in converts 4 to "4" and checks for a property with that name on [1,2,3,4]. There isn't one, so the result is false.


    The conversions of numbers to strings mentioned above are per the specification, but JavaScript engines optimize arrays where possible, and if dealing with such an optimized array, it can avoid converting the number to string before doing the lookup.