views:

43

answers:

1

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?

FWIW, I am using Mozilla's Spidermonkey runtime.

+2  A: 

It's no problem in JS, thats one of the benefits of a language with dynamic objects ;)

The only reason for it to be unsafe is if you have created dependencies to the properties you delete in code elsewhere.

Also a note about deleting properties. Some properties are undeleteable (native properties spring to mind) and if the property doesn't belong directly to the instance but inherited it from the prototype, it's also undeletable unless you delete it on the prototype directly (unless it inherited the property from another object... and so on).

But yeh, if you had set the property/attribute directly on an object yourself, it's safe.

BGerrissen
good point, i'll add a hasOwnProperty() to the example code
Joe Shaw