Reputation: 4019
I consider myself a JS veteran but just now for the first time I have realised that the for ... in
loop does something very different from the in
operator:
"length" in []; // true
for (k in []) { if(k == "length") alert(); }; // k will never be "length"
So this brings me to my question: why is the in
operator at all present in the for ... in
loop?
Imho it is totally misleading, as it does different things. Also the notion that first the for
operation makes the JS engine take all enumerable properties and then on that subset the in
operator is used is imho wrong: simply because the in
operator accepts all possible properties whether prototype or own, whether accessor- or data-properties. So how does it filter anything out if for
has already reduced to enumerable object properties?
Upvotes: 1
Views: 87
Reputation: 665286
So this brings me to my question: why is the
in
operator at all present in thefor ... in
loop?
It isn't. The in
token in the for … in
loop construct is not an operator, just as much it is not one in the expression
x = {in: 5}.in
It's just one of the tokens that distinguishes a for ( … in … )
from a for (…; …; …)
loop. Given that there is no for (…)
statement, the role of the in
token in a relational expression never collides with this.
Upvotes: 3