Javascript delete property vs. nullifying it?

Let's start with a simple object:
var person = {
   firstName: 'John',
   middleName: 'D.',
   lastName: 'Doe'
}

The most common way to get rid of a property value is to nullify it or make it undefined.
Ex.
person.middleName = null;
or
person.middleName = undefined;

var person = {
   firstName: 'John',
   middleName: null,
   lastName: 'Doe'
}


Other way is to just delete it.

The delete operator does a different job by removing the whole property, returning true or false to indicate the success of the operation. In fact the deletion does not do anything related to freeing memory or releasing resources. It is just removing the property so it no longer appears in the object skeleton.
Ex.
delete  person.middleName;

This will result into
var person = {
   firstName: 'John',
   lastName: 'Doe'
}
Obviously deleting a property may help in cases when you need to enumerate the object properties and property must not appear any more. 

Deleting an array element is a different thing. The deleted element gets undefined, but the actual array length is not changing. The actual usage difference between using 'undefined' or delete operator appears to be in object properties. 

No comments:

Post a Comment