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
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 : falsein the current version of JavaScript usingdefineProperty. 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:
You don’t actually need to include
enumerable : false—it isfalseby default when callingdefineProperty.