The delete operator is arguably an old language feature of JavaScript. As it literally means, it wants to destroy something, but what exactly can be destroyed?
delete 0
When delete 0 is executed, will it be destroyed from the execution system from 0?
Obviously not, its real purpose is to delete a property reference of an object.
delete object.property
delete object['property']
Generally, successful deletion will return true and failure will return false, but there are some exceptions.
Own properties
The delete operator only works on its own property. If there is a property with the same name on the prototype chain, this property will be skipped.
Non-existent property
If the deleted property does not exist, delete will have no effect, but will still return true.
const object = {};
delete object.name; // true
Non-configurable property
Non-configurable properties cannot be removed.
In non-strict mode, removing a non-configurable property of itself will return false, but in strict mode, it will throw a TypeError.
Properties declared by var, let, const
In the global scope, neither properties declared with var nor functions declared with function declarations (non-function expressions) can be deleted. This is because both the declared properties are mounted on the window and are non-configurable, so the logic of the previous item will be followed when deleting.
In addition, properties declared with var, let, const and those functions cannot be deleted, either in the global scope or in the function scope.
{
let object = {
name: 1,
};
function getName(obj) {
return obj.name;
}
console.log(delete object); // false
console.log(delete getName); // false
}
In non-strict mode, false is returned, but in strict mode, a SyntaxError is thrown instead of a TypeError.
Array property
First of all, the length property of the array is not configurable, so deleting it in strict mode will throw a TypeError.
In addition, when deleting an array element, the deleted item will be empty.
If you want to modify the original array, you can use Array.prototype.splice()
Conclusion
The real purpose of the ‘delete operator’ in JavaScript is to delete a property reference of an object. It can behave strangely in some special cases, so it’s best to only use it to remove configurable properties that exist on the object itself.
Besides that, please note that the ‘delete operator’ has nothing to do with freeing memory directly (compared to delete in C++), this is because the runtime environment of the JavaScript manages memory automatically. For more information on programming language memory management check out my previous article.
If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!