Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Re https://twitter.com/rauschma/status/1086903633134931968 -

I usually describe it as (roughly):

JavaScript is a purely pass-by-value language. Variables (and properties, and parameters) contain values. Assigning one variable's value to another, passing it into a function, etc., copies the value:

a = 1;
b = a;

That copies the value 1 from a into b; now a and b each have a 1 in them. There's no enduring link between a and b, they just happen to contain the same value.

The value stored in a variable (etc.) for an object is an object reference, not the object itself. An object reference is a value telling the JavaScript engine where the object is, elsewhere in memory. You never see the actual value of an object reference, but you can imagine it as a unique number identifying the object. So:

a = {};
b = a;

...copies the value (the object reference) from a into b; now a and b each have that same reference in them. As before, there's no enduring link between a and b, they just happen to contain the same value. The object isn't copied, just the value referring to it (the object reference).

Usually with a diagram, e.g.:

Suppose you do this:

let a = {foo: "bar"};
let b = null;

...at that point, you have something like this in memory (leaving out a lot of details):

                   +−−−−−−−−−−−−+
[a = Ref5461]−−−−−>|  (object)  |
                   +−−−−−−−−−−−−+
                   | foo: "bar" |
                   +−−−−−−−−−−−−+
[b = null]

Then if you do:

b = a;

...you get this:

[a = Ref5461]−−+
               |   +−−−−−−−−−−−−+
               +−−>|  (object)  |
               |   +−−−−−−−−−−−−+
[b = Ref5461]−−+   | foo: "bar" |
                   +−−−−−−−−−−−−+

I find that usually helps people understand this stuff in a pragmatic way that lets them get work done. It is somewhat at odds with the more theoretical meaning of "value" as used in the spec and sometimes in computer science in general, and if the audience seems up to it, I'll mention that. But thinking of object references as just like numbers greatly simplifies the mental model. (I do avoid saying "memory address". :-) Not least because it's inaccurate and misleading.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment