Pass by Reference - can same name be used for different variables?

Here’s the wording from section on Pass by Reference

When we passed spaceship into that function, obj became a reference to the memory location of the spaceship object, but not to the spaceship variable. This is because the obj parameter of the tryReassignment() function is a variable in its own right. The body of tryReassignment() has no knowledge of the spaceship variable at all!

Reading it seems to suggest that the obj parameter is a variable in its own right.

And this variable has no notion of the values assigned to the object spaceship which has its own key-value pairs

so at the time we pass spaceship as an argument for the anonymous function then at that time there are two spaceship variables
one that is dealt with in the tryReassignment variable
and the other is the spaceship which is an object with key-value pairs.

This sound wrong.
What do I get wrong??

Variables are stored in a different place in memory than the objects they point to. When we write, obj = spaceship we are not assigning spaceship to object, but the address of the object that it points to. Now both variables point to the same address (same object) without any other connection.

We don’t pass arrays or objects to a program, only their address, or reference. The objects stay where they are, and their scope is that of the function or context where they are first declared. That’s why we can change an array or object in a function and not have return anything. The object in outer scope is the one that gets changed.

The variable name we use in a parameter is locally declared behind the scenes with var which gives it local scope. Even if we name the parameter the same as a global variable, they are different variables in different scope. Only thing is, we can no longer access the global unless we prefix it with window since the parameter is shadowing the global.

Thank you @mtf
Something to contemplate.
But I like this:

This is probably something to do with how memory works?
Thank you

1 Like

Yes, it has to do with the way JS stores primitives and reference objects. One is stored in the call stack, the other in a heap. Look this up for a more technical background.

Just found this one, but there will be plenty more, I’m sure. It’s a topic that comes up a lot.

1 Like