Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  121] [ 7]  / answers: 1 / hits: 23170  / 14 Years ago, wed, august 11, 2010, 12:00:00

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.)


More From » loops

 Answers
13

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.


[#95949] Monday, August 9, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;