Introduction

Something I wish I had understood early on in my JavaScript programming career is how object assignment works and how it’s different from primitive assignment. This is my attempt to convey the distinction in the most concise way possible!

Primitives vs. Objects

As a review, let’s recall the different primitive types and objects in JavaScript.

Primitive types: Boolean, Null, Undefined, Number, BigInt (you probably won’t see this much), String, Symbol (you probably won’t see this much)

Object types: Object, Array, Date, Many others

How Primitive and Object Assignment Differ

Primitive Assignment

When you assign a primitive value to a variable, the value is created in memory and the the variable points to that value in memory. Primitives can’t be modified; in other words they are immutable.

Let’s look at the following code:

const a = 'hello';
let b = a;

In this case, the string hello is created in memory and a points to that string. When we assign b the value of ab also points to the same hello string in memory. Now what if we assign a new value to b?

b = 'foobar';
console.log(a); // "hello"
console.log(b); // "foobar"

This makes sense; a new string (foobar) is created in memory and now b points to that string. a still points to hello in memory. Importantly, nothing we do to b will affect what a points to because primitive values are immutable.

Object Assignment

Object assignment works similarly in that the object is created in memory and the variable points to that object. However, there is one key difference: objects can be mutated! Let’s take a look at a new example.

const a = { name: 'Joe' };
const b = a;

The first line creates the object { name: 'Joe' } in memory and then assigns a reference to that object to variable a. The second line assigns a reference to that same object in memory to b.

Again, this is a big deal for objects because they’re mutable. Let’s now change the name property of the objec that b is pointing to:

b.name = 'Jane';
console.log(b); // { name: "Jane" }
console.log(a); // { name: "Jane" }

That’s right! Since a and b are assigned a reference to the same object in memory, mutating a property on b is really just mutating a property on the object in memory that both a and b are pointing to.

#javascript #programming

Object Assignment vs. Primitive Assignment in JavaScript for Beginners
1.20 GEEK