Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for-in and built-in properties

Tags:

javascript

Why are the built-in properties on javascript objects not iterated through when using the for-in control block, while user-defined properties are?

For example:

var y = 'car';
for (var j in y)
{
    console.log(j);
}

Will print:

0
1
2

Even though String.prototype has properties for length, replace, substring, etc.

If extending the prototype, however, any new properties are iterated over:

String.prototype.foo = 7;
var y = 'car';
for (var j in y)
{
    console.log(j);
}

Will print:

0
1
2
foo
like image 695
Jeremy Elbourn Avatar asked Jan 29 '26 23:01

Jeremy Elbourn


2 Answers

Basically, the built-in properties are marked as "non-enumerable" internally. This means, naturally, they aren't enumerated.

Edit: as Andy kindly pointed out, you can set enumerable : false in the current version of JavaScript using defineProperty. However, this seems to not be supported Opera at all; IE 8 only supports it on DOM objects and Safari only supports it on non-DOM objects (defineProperty on MDN (look towards bottom of file for browser support)).

All this cross-browser fun means that you probably shouldn't rely on this behavior if you need consistent browser support.

Here is how you could define a non-enumerable property:

Object.defineProperty(String.prototype, "foo", {value : 7, enumerable : false});

You don't actually need to include enumerable : false—it is false by default when calling defineProperty.

like image 191
Tikhon Jelvis Avatar answered Feb 01 '26 15:02

Tikhon Jelvis


There is propertyIsEnumerable method, which returns a boolean indicating if the internal ECMAScript DontEnum attribute is set (also note the terrible disagreements amongst implementations). As said above, you cannot set DontEnum, but only query via propertyIsEnumerable.

like image 36
user422039 Avatar answered Feb 01 '26 13:02

user422039



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!