Removing a Property in JavaScript

Remove a JavaScript object property with delete

delete
1
2
3
var thing = { "prop1": 1, "prop2": 2 };
delete thing.prop1;
expect(thing).toEqual({ "prop2": 2 });

Simple, done, use it. End of blog post :)

If it’s not possible to use dot notation (which you always should where you can), you can delete your property like this:

delete
1
2
3
var thing = { "prop1": 1, "prop2": 2 }, i = 1;
delete thing["prop" + i];
expect(thing).toEqual({ "prop2": 2 });

What about deleting variables and functions?

This is JavaScript, it’s not possible to delete variables e.g.

no no no
1
2
var thing = "something";
delete thing; // no no no

It’s not possible to delete functions declared in this way either.

The DontDelete attribute

There are also some attributes that can be set on properties to prevent their deletion misuse. DontDelete is an example of these, which is present in the length property:

no no no
1
2
var thing = "something";
delete thing.length; // no no no

Strict mode

Obviously since my post on JavaScript Strict Mode you’re all using it. This has an impact on the delete command (for better), which would cause the above example attempting to delete the .length property to throw an error, as it should.

Happy strict deleting.