There are two things at play here : activation records, and objects on the heap.
You start off with an activation frame for global variables:
globArray : undefined
and the heap contains literals that appear in your code
ptr0 : "craig"
ptr1 : "silva"
where ptr0
, ptr1
, etc. are just addresses or labels that refer to a particular location in memory.
When you call test()
, the interpreter pushes a new activation frame which contains boxes for local variables.
globArray : undefined
---------------------
names : undefined
Then the interpreter evaluates ["craig", "silva"]
which creates an object on the heap.
ptr0 : "craig"
ptr1 : "silva"
ptr2 : [ &ptr0, &ptr1 ]
so ptr2
now is a location in memory containing an array that points to two values.
This memory location is now stored in the names
location in the activation record, so your call stack looks like
globArray : undefined
---------------------
names : &ptr2
The assignment names = ...
does not change the heap, just the activation record.
Next globArray = names
copies the contents of one activation record entry to another.
globArray : &ptr2
---------------------
names : &ptr2
Then the call to test
ends so that activation record is discarded, leaving
globArray : &ptr2
where the global globArray
points to the object created during the call to test
.
The end of the function just changes the active activation records, not the heap, so the heap still looks like
ptr0 : "craig"
ptr1 : "silva"
ptr2 : [ &ptr0, &ptr1 ]
so ptr2
is still the same array.
so "names" is gone, right?
names
(the entry in the activation record) is gone, but the object it pointed to is not since it is still pointed to by the globArray
entry in an active activation record.
Then later I call test2, but it DOES show the elements! So it must have COPIED the whole object
No, it just copied a reference to the location in the heap occupied by that object. No new object was created since the heap was not changed, and the heap is where all objects are created.
What and where are the stack and heap? might be of interest.