Primitives vs. Objects

A brief comparison of primitives and objects in JavaScript.

We know that numbers, strings, booleans, nulls and undefined are primitive values in JavaScript. Everything else is considered an object. A big difference between primitive values and objects is that variables containing primitives actually store data inside the variable themselves. However, variables with objects only store a reference to where the actual object is located in memory.

Let’s look at the following example to understand the implications of this difference:

As you can see, we have two variables with primitive values (a and b) and two variables referencing an object (obj1 and obj2). When we changed a to equal 43, b still remained equal to 23. This is because the values stored in variables a and b are different.

However, when we changed the age property of obj1 to equal to 3o, this also changed the age property of obj2. Why? because when we created obj2 and set it equal to obj1(var obj2 = obj1), we did not create a new object. Instead, we created a new reference that points to an object — the same object as obj1.

That means that obj1 and obj2 both refer to the exact same object. And so, when you change the age property of obj1, you are also changing the age property of obj2, and vice versa.

You can imagine the importance of understanding this difference, as it can lead to problem solving unexpected bugs and quirks in your code.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.