Pass by reference

Have a question about this lesson: lesson

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

  • When we did the reassignment in the body of tryReassignment() , the obj variable came to refer to the memory location of the object {'identified' : false, 'transport type' : 'flying'} , while the spaceship variable was completely unchanged from its earlier value.’"

This is very difficult to understand. What the lesson is trying to say in the first part, is that not the object spaceship is thrown into the function, but a temporary new copy of the object as the variable “obj” ?

Yes, its phrased a bit confusing.

Objects and arrays are passed by reference. We can do with a simple example:

const objFunction = (inObj) => {
   inObj['b'] = 2;
}

myObj = {};
myObj['a'] = 1;
console.log(myObj);
objFunction(myObj);
console.log(myObj);

the object is actually changed, because its by reference. When we would pass an integer, a copy is made, so changes made are not reflected on the global variable. Do i need to make an example of that too?

1 Like