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
:
Let desc be the result of calling the [[GetOwnProperty]] internal method of O passing P as the argument.
If desc is undefined, return false.
Return the value of desc.[[Enumerable]].
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 in
operator:
Return the result of calling the [[HasProperty]] internal method of rval with argument ToString(lval).
And if you look at the [[HasProperty]]
internal method:
Let desc be the result of calling the [[GetProperty]] internal method of O with property name P
And here you can see the difference. The in
operator 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.defineProperty
method). If you define a non-enumerable property, it will be returned by the in
operator, but obviously not by the propertyIsEnumerable
method. Here's a fiddle that demonstrates the difference.