akonsu
akonsu

Reputation: 29536

delete a property or set it to null?

Maybe this is a naive question, but I have to ask for expert opinions...

I often use temporary properties in objects that indicate the object's state. One of the states is when the property evaluates to false. For example:

// inside some method:
this.timer = setTimeout(function () {
  console.log('hello world');
}, 1000);

...

// inside another method:
if (this.timer) {
  clearTimeout(this.timer);
  this.timer = null;
}

When I clear my timer, I can either assign null to it as I do above, or I can delete it from the object:

delete this.timer;

I am not sure which way is preferred. What are disadvantages of deleting the property rather than setting it to null?

EDIT:

I of course realize that when I delete a property, the property goes away and when I set it to either null or undefined it is still there. The question is is it an accepted practice to delete a property in circumstances as above. I suppose not because it is slower...

Upvotes: 1

Views: 1701

Answers (3)

rink.attendant.6
rink.attendant.6

Reputation: 46208

Deleting the property removes the property whereas setting it to null makes it… null. Both are conceptually different:

  • With deleting the property, you're inferring that the timer no longer exists.
  • Setting it to null would infer that the timer no longer has a value, but still exists.

Upvotes: 2

worldask
worldask

Reputation: 1837

delete will really remove the property from its owner, in your code is this object.
But set property to null or undefined won't do that.

You can check it using this:

for(var i in obj) {
    if (obj.hasOwnProperty(i)) {
        console.log(i, '' + obj[i]);
    }
}

Upvotes: 0

Nicolas Albert
Nicolas Albert

Reputation: 2596

With delete this.timer, you remove the timer key of your current this object → the key doesn't exist anymore.

With this.timer = null, you assign the null value to the timer key → the key still exists.

If you transform your this object to JSON, the timer can be here or not, same for the for (key in this) {…}

Upvotes: 0

Related Questions