Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for in loop and the delete operator

Tags:

javascript

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.

like image 902
goat Avatar asked Aug 21 '12 18:08

goat


1 Answers

Interesting question. The answer lies in the specification (emphasis mine):

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.

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:

> Object.keys({a:0, 0:1});
  ["0", "a"]

However, even if you add alphabetical keys:

var obj = {a:0,b:0};
for (var k in obj) {
    obj['c'] = 0;
    console.log(k);
}

c does not seem to be traversed, the output is a b.

Firefox shows the same behaviour, although keys are stored in insertion order:

> Object.keys({a:0, 0:1});
  ["a", "0"]
like image 72
Felix Kling Avatar answered Oct 09 '22 12:10

Felix Kling