Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to delete an object property while iterating over them?

When iterating over an object's properties, is it safe to delete them while in a for-in loop?

For example:

for (var key in obj) {     if (!obj.hasOwnProperty(key)) continue;      if (shouldDelete(obj[key])) {         delete obj[key];     } } 

In many other languages iterating over an array or dictionary and deleting inside that is unsafe. Is it okay in JS?

(I am using Mozilla's Spidermonkey runtime.)

like image 827
Joe Shaw Avatar asked Aug 11 '10 21:08

Joe Shaw


People also ask

How do you remove a property of an object?

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

What happens when you delete an object?

You don't actually delete objects with del , you delete references to objects. When there are no more references to an object, it is garbage-collected and only then does it (and any references inside it) get deleted.


1 Answers

The ECMAScript 5.1 standard section 12.6.4 (on for-in loops) says:

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 I think it's clear that the OP's code is legal and will work as expected. Browser quirks affect iteration order and delete statements in general, but not whether the OPs code will work. It's generally best only to delete the current property in the iteration - deleting other properties in the object will unpredictably cause them to be included (if already visited) or not included in the iteration, although that may or may not be a concern depending on the situation.

See also:

  • MDN on for..in
  • MDN on browser quirks re: iteration order
  • In depth page on delete operator issues

None of these really affects the OP's code though.

like image 86
TomW Avatar answered Sep 18 '22 17:09

TomW