Copying by value vs. copying by reference

What’s the difference, and how does this work in JavaScript?

I am absolutely loving Nicholas Zakas’s The Principles of Object-Oriented Javascript. It’s helped solidify a lot of the concepts that are touched on in the bootcamp curriculum.

One that’s been a little fuzzy in my head in the past few weeks has been copying by value vs. copying by reference — but I think I finally have it down now!

If you assign a primitive value to a variable, and then assign that variable to a second variable, the primitive value is copied by value. For example:

str1 = "cat"; 
str2 = str1;
str2 = "dog";
// str1 still equals "cat"

str1 and str2 each get their own copy of "cat" stored separately in memory.

In JS, primitive types include strings, numbers, and booleans (as well as undefined and null).

If you assign a reference value to a variable, and then assign that variable to another variable, that value is copied by reference. For example:

var obj1 = { animal: "cat" }; 
obj2 = obj1;
obj2.animal = "dog";
// now obj1.animal equals "dog", too

Both obj1 and obj2 point to the same location in memory.

In JS, objects are reference types (and hence functions and arrays are reference types, too).


Originally published at www.dorothy.codes on January 8, 2016.

Like what you read? Give Dorothy M a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.