• Web Developer
  • Posts
  • The Secrets of the 'delete' Operator in JavaScript

The Secrets of the 'delete' Operator in JavaScript

What Can Be Deleted in JavaScript

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 globalThis 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.

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.

Additionally, when you remove a property from an object, and this property’s value is an object without any remaining references, the JavaScript runtime will eventually automatically free the object owned by that property. For more insights into programming language memory management, see my previous article:

If you find this helpful, please consider subscribing for more useful articles and tools about web development. Thanks for reading!

Reply

or to participate.