Why aren't toString and hasOwnProperty (etc.) displayed in for-in loops in JavaScript?

I talked about hasOwnProperty with another developer, and how you should use it in for-in loops in javascript, and he had a good question. When you run a for-in loop, why doesn't toString, hasOwnProperty and other built-in methods appear in the loop?

+7
source share
5 answers

ECMAScript defines several properties for each property found on objects, such as prototypes. One of them is the enumerable property, and if it is set to false , then this property will be skipped.

In fact, you can control these properties using the defineProperty function:

This method allows you to precisely add or modify a property of an object. The usual addition of properties via assignment creates properties that are displayed during the enumeration of properties (for ... in a loop), the values ​​of which can be changed and which can be deleted. This method allows you to modify these additional parts from their default values.

+5
source

This is for every specification.

A for ... the loop does not go over the built-in properties. These include all built-in object methods, such as the String indexOf method or Object toString. However, the loop will iterate over all custom properties (including any overwrite inline properties).

From the Mozilla Developer Network Page for forin

It is internally based on the enumerated attribute of these properties, since you can check the EcmaScript specification (search for-in, attribute "enumerable" described on page 30)

+4
source

I am sure that these methods have an internal [[Enumerable]] attribute set to false , but I cannot find anything where this is explicitly indicated.

Update: The default value for the properties defined in the specification (unless otherwise specified) appears to be non-enumerable (see table 7 in the link below).

Further information on these attributes can be found in the specification: Property Attributes :

If true , the property will be enumerated by enumeration in-in (see 12.6.4 ). Otherwise, the property is called non-enumerable.

+4
source

Built-in properties are not enumerated, therefore toString and hasOwnProperty not enumerated. In ECMAScript 3, each user-defined method or property is enumerable. In ECMAScript 5, you can choose whether a method or property is enumerated.

+1
source

I may have misunderstood your question, but here is a hasOwnProperty example working inside a for-in loop:

 var i,o={some:"thing"};for(i in o)alert(o.hasOwnProperty("some")); 
0
source

All Articles