2

I have code like this:

const o = { x: 'hello' };
o.x = undefined;
const o2 = { ...o };
// can now ('x' in o2 === false) ?

Can garbage collector delete key after set undefined

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53
pank
  • 803
  • 1
  • 11
  • 16
  • 3
    You've set the property value to be `undefined` but the property still exists. Use `delete o.x` to remove the property entirely. – evolutionxbox Oct 03 '22 at 15:10
  • I have a problem with logger that used `JSON.stringify` that removes `undefined` values XD – pank Oct 04 '22 at 09:15

2 Answers2

2

No the key x won't be deleted, because undefined is a valid value for an object property. undefined is one of the javascript primitive types.

In order to remove the property from the object you have to use delete:

delete o.x

The string "hello" will eventually be freed by the garbage collector if there is no more references to it.

You can find a good explanation of how the garbage collector works here.

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53
  • 1
    They didn't ask about `"hello"`, the question was whether the `x` key can be removed from the object. – Barmar Oct 03 '22 at 15:24
1

No. Even though reading a nonexistent property returns undefined, it's not the same as a property that has been explicitly set to undefined. This is because functions like Object.getOwnPropertyNames() return all the keys, not just the ones that have values other than undefined, and it would change the result. Similarly, "x" in o doesn't care about the value. In addition, an explicit property will shadow a property that's inherited from a prototype.

Also, the garbage collector doesn't remove references, it only collects objects that have no references. Exceptions are WeakMap and WeakSet, which are specifically designed to not count as references by the GC. But the above reason is why you can't get a list of the keys of a WeakMap.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You can set "x" to be non-enumerable then it won't show in Object.keys() and still exist in the object. The result of Object.keys() does not define property existence. – Tiago Bértolo Oct 03 '22 at 15:36
  • That was just an example, there's also `.hasOwnProperty()`. – Barmar Oct 03 '22 at 15:37
  • @TiagoBértolo Then `Object.getOwnPropertyNames` does? Or `"x" in o` does? Or `Object.getOwnPropertyDescriptor(o, "x")`? – Bergi Oct 03 '22 at 15:37
  • . getOwnPropertyNames() will list non-enumerable properties, Object.keys() won't. Test it yourself: `const cc = Object.create(Object.prototype,{name: { value: undefined, enumerable: false }})` – Tiago Bértolo Oct 03 '22 at 15:46
  • I already changed the answer. – Barmar Oct 03 '22 at 15:50