Do You Know Where Your Variables Are? Value vs. Reference in Javascript
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).
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:
let a = "dog"
let b = aconsole.log(a); // "dog"
console.log(b); // "dog"
console.log(a === b) // true
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.
var a = "dog"
var b = avar a = "cat"console.log(a); // "cat"
console.log(b); // "dog"
console.log(a === b); // false
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:
console.log("Fido" === "Fido"); // trueconsole.log({name: "Fido"} === {name: "Fido"}); // false
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
var array = ["dog"];
var newArray = array;
We have now given two objects the same location in memory. So if we change either array, the other will be changed as well.
array.push("cat");console.log(array); // ["dog", "cat"]
console.log(newArray); // ["dog", "cat"]
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:
var dog = {name: "Fido"}
var sameDog = {name: "Fido"}
console.log(dog === sameDog); // FALSE!// BUTconsole.log(dog.name === sameDog.name); // TRUE!
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!