Why does the "delete" operator not remove references to a deleted Javascript property?

Asked

Viewed 47 times

4

I am reading a book about data structure in Javascript and came across the following situation: why delete does not delete a reference value? I will give an example to be clear.

const items = { a: 1, b: { x: 2 } };
const b = items.b; // Note que `b` não é primitivo, mas sim uma referência

items.b.x = 'changed';

// Por ser uma referência, `items.b` e `b` apontam para o mesmo lugar
console.log(items.b); // { x: "changed" }
console.log(b); // { x: "changed" }

delete items.b; // Por que isso não deleta tudo?

console.log(items.b); // undefined
console.log(b); // { x: "changed" } -- Não deletou

On the last line, why the value of b remained intact instead of resulting in undefined, since the value has been deleted?

1 answer

4


Because the delete does not have the function of "erase" the existence of a memory value, only remove a property from an object.

Of documentation:

The operator delete removes a property from an object. If there are no more references to the same property, the value is eventually automatically released.

It is important to reiterate two points:

  • The delete does not have the function of deleting the existence of a value, but rather removing properties of objects - so much so that delete does not work to delete, for example, local variables.
  • The delete does not remove references to the removed property. If there are still references, the GC will not collect the value just because it has been removed from an object.

For more details, refer to this documentation. Article Understanding delete also has some interesting observations. And of course the section § 12.5.3 of the specification, which formalises the.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.