JavaScript: Invaluable Properties - When and Why?

I recently came across the problem of using for..in loops on arrays in JavaScript.

According to the answers in this question, for..in is intended to enumerate object properties, including inherited ones.

If so, why do we have the ability to define properties as non-enumerable using Object.defineProperty? Is this not against the goals? Or is this considered bad practice and should be avoided?

Also, why should we first iterate over all the properties this way (for example, using the for..in loop)? When can this come in handy?

And why not define all (Array) extension prototypes as non-enumerable and continue to use for..in with arrays?

+5
source share
1 answer

The problem is that there is only one namespace for the properties of the object (currently the Symbol function is ignored in ES2015). There are some properties of the objects you want to list, and some are not. Properties that contain object data and relationships with other objects share this namespace with method names.

The for ... in loop looks not only at the properties of the object directly involved, but also at the prototype chain. This is probably the most likely use for non-enumerable properties: the methods you might want to place on the prototype probably don't need to be listed.

For me, the real reason not to use for ... in when you iterate through the numeric-name properties of an Array instance is that there is no guarantee that you will iterate over the indexes in any particular order. Although most runtime systems give numeric-name properties in obvious order, the specification for the language absolutely does not require this to be the case. Using an explicit numerical index in a regular for loop, you explicitly control the iteration order.

People who write JavaScript code for use in contexts where other code will work that they don’t have control over (think that sites that support ads or sites with many metrics tools) know that relying on built-in prototypes should not be polluted random junk, extremely unreasonable. Using for ... in puts your code in the grip of the worst encoder contributing to this third-party code.

Modern implementations have Object.keys() , which returns enumerable "proper" object property names; that is, property names directly on the object, and not a single prototype chain.

+6
source

All Articles