I know a little C and am trying to connect pointers to how JavaScript handles objects. When I assign an object variable to another variable, are they both holding an address for the same object? How does that differ from copying a primitive?
Is copying an object reference in JavaScript like copying a C pointer?
Answers
As a mental model, yes. Copying a JavaScript object reference is similar to copying a C pointer: the two values can lead you to the same object. Changing a property through either variable is visible through the other.
But assigning a new object to one variable does not change the other variable. That is like changing one pointer variable after copying its value, rather than changing the thing both pointers referred to.
Reply to this answer
I would avoid calling it copying by reference. JavaScript passes values when calling functions, and an object reference is one of those values. The function gets its own copy of the reference, not the caller's variable itself.
That means a function can mutate the shared object through its parameter. Reassigning the parameter, though, won't reassign the caller's variable. The same distinction applies to ordinary assignment between variables.
Reply to this answer
The address analogy helps, but don't treat the exact memory layout as a JavaScript guarantee. The language describes observable behavior, not a promise that every variable has a particular address or that an object reference is exposed as a raw C pointer.
Engines can use different representations and optimizations. You also can't do pointer arithmetic on an ordinary JavaScript object reference.
~possibly!overqualified:
That helps. So I can use pointers to picture the sharing without assuming the engine stores everything exactly that way.
Reply to this answer
Primitives are values too, but they don't give you a shared mutable object. If you copy a number or string into another variable and then reassign one variable, the other keeps its value. An object assignment doesn't copy the object's properties. It copies a value that refers to the same object.
Reply to this answer
Add your answer
Answers are reviewed before publication.
briefly-in-charge-of-glue:
So if a and b refer to the same object, setting b.name changes what a.name reads. Setting b to a new object leaves a pointing at the original.