FAQ: Objects - Pass By Reference

Update! A friend of mine who’s a Senior JS Engineer explained this to me and I get it now.

The crucial point, for me, was understanding that when you pass an object into a function to mutate a property on it, the “object” parameter in the function declaration is what gets deferenced(behind the scenes) and replaced with a reference to the original object. THIS is what allows you to mutate the original object. If you try to reassign it yourself, all you’re doing is reassigning the object parameter; it never gets deferenced by the program and assigned to reference your original object. Still a tricky concept and an awkward explanation on my part, but I was finally able to internalize it this way.

Made a diagram in an attempt to help future people who are still stuck like me. The second purple paragraph is the key point to me, and explains an invisible step that happens on line 17, which maintains the pass-by-reference to the original object and makes the mutation possible.

1 Like

The third bullet point completely lost me. I understand that primitives are passed by value, and objects are passed by reference, but what is this talking about when it says the parameter is its own variable and it became a reference itself? I’ve not seen this stated in any other resource, and I’ve spent a whole day just on this

The point seems to be that even if you reassign obj to be a different object, it does not change spaceship.

But obj is just a placeholder no? Just like any other parameter to a function. Why is the parameter relevant now? Why does it “become a reference to the memory location of the spaceship object but not the spaceship variable”…what does that even mean?

I think that there’re making the point that
objects are passed by reference,
so obj would be a reference to spaceship,
but when you reassign obj, then you are changing what obj is a reference to,
so obj is no longer a reference to spaceship.

parameters act just like variables inside the function.

I think I finally get it now. So parameters take the same reference as their corresponding argument.

Also, this lesson was badly explained imo. It assumed the reader knows about memory allocation and under the hood workings of assigment. Not helpful at all