I noticed that when enumerating the properties of an object, that it seems like a snapshot of the current properties is taken at start of the loop, and then the snapshot is iterated. I feel this way because the following doesn’t create an endless loop:
var obj = {a:0,b:0}, i=0;
for (var k in obj) {
obj[i++] = 0;
}
alert(i) // 2
demo http://jsfiddle.net/kqzLG/
The above code demonstrates that I’m adding new properties, but the new properties won’t get enumerated.
However, the delete operator seems to defy my snapshot theory. Here’s the same code, but deleting a property before it gets enumerated.
var obj = {a:0,b:0}, i=0;
for (var k in obj) {
i++;
delete obj.b;
}
alert(i) // 1
demo http://jsfiddle.net/Gs2vh/
The above code demonstrates that the loop body only executed one time. It would have executed twice if the snapshot theory were true.
What’s going on here? Does javascript have some type of hidden iterator that it uses, and the delete operator is somehow aware of it?
— I realize that I’m assuming something about iteration order- specifically that iteration occurs based off of property insertion time. I believe all browsers use such an implementation.
Interesting question. The answer lies in the specification (emphasis mine):
So it is explicitly specified that a deleted property must not be traversed anymore. However, the behaviour for adding a new property is implementation dependent, most likely because it is not defined how properties should be stored internally.
For example in Chrome, it seems that numeric properties are stored before alphabetical ones:
However, even if you add alphabetical keys:
cdoes not seem to be traversed, the output isa b.Firefox shows the same behaviour, although keys are stored in insertion order: