I encountered the method o.propertyIsEnumerable(x) in Javascript code. I understand it as a synonym for the x in o construct. Is there a difference? If so, could you show when to use the first construct and when to use the second construct on some practical example?
var o = {};
o.x = 1;
o.y = 2;
if ("x" in o) {
// some code
}
if (o.propertyIsEnumerable(x)) {
// some code
}
The easiest way to work out things like this is to follow the algorithms in the spec. This is what it tells us about
propertyIsEnumerable:As you can see, it will call the
[[GetOwnProperty]]internal method of the object in question. That simply returns the value of the specified property from the object itself (not from anything in its prototype chain).Now let’s have a look at the
inoperator:And if you look at the
[[HasProperty]]internal method:And here you can see the difference. The
inoperator results in the use of the [[[GetProperty]]internal method][4], instead of the[[GetOwnProperty]]method, and that means it will find properties on objects down the prototype chain.The other major difference is that you can define non-enumerable properties on an object (with the
Object.definePropertymethod). If you define a non-enumerable property, it will be returned by theinoperator, but obviously not by thepropertyIsEnumerablemethod. Here’s a fiddle that demonstrates the difference.