views:

68

answers:

3

So I write a short function to remove members from an object that have falsy values:

for (var key in object) {
    if (!object[key]) {
        delete object[key];
    }
}

A couple days later I check source control and someone has changed this to:

var newObject = {};
for (var key in object) {
    if (object[key]) { newObject[key] = object[key]; }
}
return newObject;

There's no comments on the check-in and the guy is not here today at work.

Which implementation is better? What are the performance implications of each method?

+3  A: 

You cannot delete a property on an object that it inherits from a prototype. So in some cases your code may fail to work as expected.

Source

Yacoby
+2  A: 

You cannot delete a property of an object that it inherits from a prototype (although you can delete it directly on the prototype).

In the second example, a falsy property inherited from a prototype will not be copied to the newObject.

Further reading:

Daniel Vassallo
A: 

I think your code reads much more intuitively. Maybe he just didn't want to change the original object?

Joe Martinez
Not true, see Daniel's and Yacoby's answers.
Marcel Korpel
Those answers and mine are not mutually exclusive. Well, at least they may not be. We don't have enough context to make a determination.
Joe Martinez