I have the following code:
function createPersone(gender){
let localPerson = new Object();
localPerson.gender = gender;
return localPerson;
}
let globalPerson = createPerson("female");
In the function is created a reference to the object, localPerson contains the address where the created Object is in the memory. When localPerson is returned this address is copied into globalPerson. However localPerson has scope function thus it should be destroyed but its content is an address, is the one to whom the address points (namely the object) also deleted? Deletion of object should be gouverned from garbage collection. In this case can I assume like safe the instruction let globalPerson = createPerson("female"); and why? What happen behind the hood?
localPersonis destroyed but the object remains, since it's still referenced byglobalPerson. If that didn't work, then probably half (if we are being very modest) of all JS code ever would just fail, since a function execution would finish and any objects it had will be cleared out even if they shouldn't be.