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.)
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.
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.
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:
None of these really affects the OP's code though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With