Do You Know Where Your Variables Are? Value vs. Reference in Javascript

Image for post
Image for post
Photo by 🇨🇭 Claudio Schwarz | @purzlbaum on Unsplash

One of the most deceptively simple concepts in Javascript is the idea of Value vs. Reference. Understanding how data types behave is important for debugging code on the job, as well as during tech interviews, as this is a question that seems to come up often.

Let’s first rewind to Javascript 101. There are two categories of data types in Javascript, primitives (null, undefined, string, boolean) and objects (object, array, function).

Image for post
Image for post
Photo by Alexander Sinn on Unsplash

While it tends to be forgotten, data types in the two categories are passed differently when assigning variables. Let’s look at a straightforward example first:

Makes sense, right? Of course. Strings are primitive data types so when we assign them to a variable, we say we copy them by value; that is, that variable contains the actual value of that data type. And, importantly, what is done to one variable is always completely independent of another when they contain primitive data types.

In the example above, we changed a while b was unaffected. Fantastic! Nothing really mind blowing there. But NOW we get to objects, and this is slightly less straightforward.

When we assign an object (and this goes for actual objects, as well as arrays and functions) to a variable, that variable does NOT “contain” the value, as above; what happens is that the variable will point to a location in memory where that object is held. Because of this, we say that objects are copied by reference.

Simple example:

When we write something like newArray = [], the variable newArray receives the “address”, or location, of that array in memory, not any particular value. That “address” does not change, it is the array in memory that will change if anything is done to it.

Importantly, if we do something like

We have now given two objects the same location in memory. So if we change either array, the other will be changed as well.

In order to compare objects, probably the easiest thing to do is to turn them into strings and then compare those strings. Alternatively, with actual objects, you can compare the values of keys, like so:

Many coding interviews test job applicants on this idea of value vs. reference, so it’s definitely a good thing to get comfortable with it!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store