Search code examples
javascriptws

Does the Javascript garbage collector delete unused key/value pairs?


I have a websocket system where I have an object called sessions, the key is the name of the session and the value is an array of the websockets while using the ws js library. I want to know if the garbage collector automatically deletes unused key/value pairs like old sessions or if I have to do it manually with the delete keyword.


Solution

  • No.

    The garbage collection will clean up valies when there are no references left to them.

    References can be object properties or variables.

    A reference will only go away if the variable or property is overwritten with a new value, a property is expicitly deleted or if a variable falls out of scope (e.g. the function if it declared inside finished without returning a closure).


    In your example:

    sessions will be a reference to your object. It won't go away because you always have a reference to your collection of sessions.

    Inside that object the properties pointing at the arrays won't go away because the object still exists.

    If you want to delete one of the values of the object then you need to do so explicitly.