Value vs Reference Explanation

Let's re-write the example from our last lecture:

const person = {
	firstName: 'Jon',
	lastName: 'Snow',
}

const otherPerson = person;

person.firstName('JOHNNY');

console.log(person); // { firstName: 'JOHNNY', lastName: 'Snow' }
console.log(otherPerson); // { firstName: 'JOHNNY', lastName: 'Snow' }

So.... what happened here? Well...

When a variable is assigned a primitive value, it just copies that value. We saw that with number and strings examples.

On the other hand, when a variable is assigned a non-primitive value (such as an object, an array or a function), it is given a reference to that object’s location in memory. What does that mean?

In this example above, the variable otherPerson doesn’t actually contain the value { firstName: 'Jon', lastName: 'Snow' }, instead it points to a location in memory where that value is stored.

const otherPerson = person;

When a reference type value is copied to another variable, like otherPerson in the example above, the object is copied by reference instead of value. In simple terms, person & otherPerson don’t have their own copy of the value. They point to the same location in memory.

person.firstName('JOHNNY');

console.log(person); // { firstName: 'JOHNNY', lastName: 'Snow' }
console.log(otherPerson); // { firstName: 'JOHNNY', lastName: 'Snow' }

When a new item is pushed to person, the array in memory is modified, and as a result the variable otherPerson also reflects that change.

We're never actually making a copy of a person object. We're just make a variable that points to the same location in the memory.

Equality

We can prove that with a simply equality check.

const person = { firstName: 'Jon' };
const otherPerson = { firstName: 'Jon' };

console.log(person === otherPerson);

What do you think? Are person and otherPerson equal? Well, they should be, right? They look exactly the same, have the same keys and values. Let's check it out:

console.log(person === otherPerson);

// FALSE

You might expect person === otherPerson to resolve to true but that isn’t the case. The reason behind that is that although person & otherPerson contain identical objects, they still point to two distinct objects stored in different locations in memory.

Now, let's create a copy of the person object by copying the object itself, rather than creating a completely new instance of it.

const anotherPerson = person;

console.log(person === anotherPerson); 

// TRUE

person & anotherPerson hold reference to the same location in memory & are therefore considered to be equal.

Awesome! We just learned that primitive values are copied by value, and that objects are copied by reference.

In the next lecture, we're going to learn how to make a real copy of an object. That will allow us to copy an object and change it without being afraid that we'll change both objects at the same time.

Complete and Continue