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
ἔρως
ἔρως18h ago
yesn't depends is there any reference to it? if there is, it isnt supposed to be garbage collected
vinicius!
vinicius!18h ago
everything defined in the global scope is not garbage collected?
ἔρως
ἔρως17h ago
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)
vinicius!
vinicius!17h ago
ooh got it thanks epic
ἔρως
ἔρως17h ago
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
let a = {};
let b = {a: a};
a.b = b
let a = {};
let b = {a: a};
a.b = b
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 this
vinicius!
vinicius!17h ago
got 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?
ἔρως
ἔρως17h ago
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
vinicius!
vinicius!17h ago
thanks again bro
ἔρως
ἔρως17h ago
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
Want results from more Discord servers?
Add your server