JS Garbage Collector
In js, primitive values don't get garbage collected, right? but if a object is set in the global scope, do they get garbage collected?
10 Replies
yesn't
depends
is there any reference to it? if there is, it isnt supposed to be garbage collected
everything defined in the global scope is not garbage collected?
it shouldnt, because it's meant to be always accessible
but i cant tell you "no" because there are situations in which data that was in the global scope is garbage collected (like when it is removed from the global scope or when set to a different value like null)
ooh
got it
thanks epic
you're welcome
but keep this in mind: javascript uses reference counting to decide what to delete
it is possible to have 2 values that depend on eachother, and that makes it impossible to garbage clean any
if you set
a = null
and b = null
, there is a chance that both will stay in memory forever
both will have a reference count of 1
but browsers may be smart enough to detect thisgot it, i was thinking the scope define what'll be collected or not,
like an object created in a closed scope can be collect after that piece of code finishes its execution
but is actually the references they have in the code
so if that same object has a reference in the global scope, it can never be cleaned
is that right?
if the object has a reference ANYWHERE, it cant be garbage collected
doesnt matter the scope
usually, leaving the parent scope does garbage collect the values
but if you return it but keep a copy of the reference somewhere else, then it may be hard/impossible to garbage collect that
thanks again bro
you're welcome
just be nice and null out anything you dont need
for example, setting
null
to a variable after you are done with the object it held