Can someone help understand?


So I’m on the pass by reference lesson and I am a little confused as to what this explanation for the code it was using as an example meant. Basically it has said that you cannot change the contents of an object within a function and I’ll provide the exact explanation here

" 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!"

What does it mean by " obj became a reference to the memory location of the spaceship object, but not to the spaceship variable."

Your replies are greatly appreciated.


Variable names are only labels, not objects, proper. When they point to an array or object they are references. The object points to the values it contains.

There is only ever one object in memory, regardless how many references we create.

a = {}
b = a

b is not a copy of a, but a reference to the same object, under a different name. If we change an item in object a, the changes can be seen in object b. Inside a function, an object reference does not have local scope unless it is created inside the function. If it is passed into the function as an argument, its scope is still global, or outer scope.

a = {a: 1, b: 2, c: 3}
b = a

function foo(x) {
  x['d'] = 4;

console.log(a);    //  {a: 1, b: 2, c: 3, d: 4}

Above I’ve shown it with order, but it could be any order since objects are not ordered like arrays.


So if the scope of the “a” object is global why cant you access it within the function ?

thanks again !


Why is it that you cannot reassign the an object within a function they explain it but not good enough I have also gotten on the forums and explained my question but they answered the obvious for me what I don’t get is how can you use a variable as parameter in JS but as soon as that variable is an object you cant … why ?


We can access it, but if we use that reference in the function then we cannot pass in any other object. Reference objects are not shadowed in functions the way ordinary objects (strings, numbers, booleans) are. We use a generic parameter so the function can accept any object, not just a.

When we pass a string, number or boolean object to a function, the parameter is a newly created object with the same value. If we alter the value then the variable points to a new location, and no longer points to the inputed value. Arrays and Objects don’t work this way. We are always accessing the object referenced in the argument.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.