Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Is it safe to delete properties on an object being iterated with 'for'

Tags:

javascript

I'm doing something like this:

var myObj = {a:1, b:2, c:3, d:4};

for (var key in myObj){
  if (someCondition){
    delete(myObj[key]);
  }
}

It works just fine in the samples I've tried, but I'm not sure if it might have an unexpected behavior in certain scenarios/browsers.

Is it ok to modify the object being iterated?

like image 417
willvv Avatar asked Jul 09 '12 19:07

willvv


1 Answers

Section 12.6.4 explains that for..in is defined in terms of the "next property":

Let P be the name of the next property of obj whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V, empty).

Since the concept "next property" is well defined even in the presence of mutation (though iteration order is not), delete during iteration does not introduce undefined behavior.

There is a corner case where delete un-masks a prototype property as in

var obj = Object.create({ x: 1 });
obj.y = 2;
obj.x = 3;
for (var k in obj) {
  if (k == 'y') { delete obj.x; }
  alert(k);
}

In this case, where you might iterate y and delete x, you should still see the x from the prototype, but if you iterated x first, then y you should not see the second x.

like image 88
Mike Samuel Avatar answered Oct 13 '22 01:10

Mike Samuel