I don’t understand the assignment operator when assigning objects (say, arrays). I’m told that as assignment operator copies the reference. However it seems like it copies the data. For example:
var globArray = [];
function test() {
var names = ["craig", "silva"];
globArray = names;
}//endFunction test
function test2() {
console.log("el1: ", globArray[0], "el2: ", globArray[1]);
}//endFunction test2
When I call TEST, it creates array NAMES and assigns the global array “globArray” to NAMES. Now it goes out of scope, so “names” is gone, right? Then later I call test2, but it DOES show the elements! So it must have COPIED the whole object, as opposed to just coping the reference.
Can someone explain this?
When your “test” function returns, you’re correct that “names” is “gone”. However, its value is not, because it’s been assigned to a global variable. The value of the “names” local variable was a reference to an array object. That reference was copied into the global variable, so now that global variable also contains a reference to the array object.
Object allocation is a global thing. When an object is allocated and referenced by a local variable, then it will be garbage-collected when the local variable disappears when its scope becomes inactive unless some other reference (direct or indirect) to the object exists. A direct reference would be a case like yours. An indirect reference can happen if the local scope “leaks” a function that includes a reference to the local variable.