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