0

I just opened chrome dev tools on stackoverflow.com and typed in the console the following

delete this;

Which returned true despite not deleting the reference.

Why does delete return true if it didn't delete anything?

enter image description here

Simon Farshid
  • 2,636
  • 1
  • 22
  • 31

1 Answers1

0

The delete operator in javascript has nothing to do with memory management, you can't use it to delete objects.

Quote from Mozilla delete page:

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory.

You can use the delete operator only to remove properties from an object, e.g:

let obj = {a: 1, b: 2};
console.log(delete obj.a); // true
console.log(obj); // {b: 2}

Why delete returns true

delete will always return true, unless the property you tried to delete is non-configurable and you aren't in strict mode (delete throws in strict mode). This includes the case where you call delete with an expression that doesn't resolve in a property reference, e.g. this or null, etc...

Example:

// Doesn't evaluate to propery access.
// But isn't a non-configurable property, so return true
console.log(delete null); // true
console.log(delete 12); // true
console.log(delete "foobar"); // true

// non-configurable own property.
// only case when delete returns false
// (or throws in strict mode)
let obj = {};
Object.defineProperty(obj, "val", {value: 12});
console.log(delete obj.val); // false
Turtlefight
  • 9,420
  • 2
  • 23
  • 40