Incognito Incognito - 1 year ago 51
Javascript Question

What are some use-cases of when `delete` has been very useful in JavaScript?

We have some questions here that discuss delete in a more abstracted way, but I'm looking for practical examples of when use of

could be used, versus doing something such as setting the property to null or undefined.

The delete operator deletes a property of an object.

What's a case of a challenge faced somewhere, that
was the best solution, versus something else?

Answer Source
Object.defineProperty(Object.prototype, "Incognito", {
  get: function() { return 42; },
  set: function() { },
  configurable: true

console.log(({}).Incognito); // 42
({}).Incognito = null;
console.log(({}).Incognito); // 42

delete Object.prototype.Incognito
console.log(({}).Incognito); // undefined

Any property which has an empty setter (Because someone thought that was a good idea) needs to be deleted if you want to get rid of it.

var hash = {
  "FALSE": undefined,
  "TRUE": null

console.log("TRUE" in hash); // true
console.log("FALSE" in hash); // true
delete hash.FALSE;
console.log("FALSE" in hash); // false

The in operator returns true for any property that exist no matter it's value. If you want it to return false you need to delete the property.

In both these cases setting it to null or undefined does nothing (Because it either has a setter that does nothing, or that's how the in operator works)