Confused about behavior of object [JavaScript]

Hello. I’m new to learning JavaScript and I’m stuck at understanding something related to object reference. I’m probably missing something little that I can’t quite grasp on and it’s driving me frustrated… I’d appreciate some insight on this, thank you. :slight_smile:

So I’ve got this snowy object literal.

let snowy = {
  "name": "Snowy",
  "breed": "Ragdoll",
  "favorite food": "Tuna fish",
  "bff": "Mimi",
  speak() {
    alert(`${this.name} says meow`);
  }
};

And then I copy its reference to mimi object.

let mimi = snowy;

Now mimi has got the properties of snowy object, right? Well, now I set snowy to null.

snowy = null;

So now snowy is set to null and returns it when it’s tried to be accessed.

But after it, when I access mimi, which uses reference of snowy, mimi returns the snowy properties prior to it being set to null. Why? Shouldn’t it return null like its referenced object does? How can it still have the properties that I removed?

Hi @ChocoJuicy and welcome to the forum.

The behaviour you are seeing is due to the fact that object are assigned by reference.
In JS you have two memory behaviour: value and reference.

Value is used on primitive types, and you can imagine something like the “variable is the value”

var a = 10
var b = 'hello'

Array, Object and Functions are assigned by reference, this means that the variable is pointing to the address in memory where that value is stored.

So when you make:

snowy = { ... }

// translate to something like

snowy = <#0000> // Some address to the memory

When you reassign snowi to a different value, you are not changing the “value” itself, but simply tell snowy to point to a different “location” in memory.

If the engine finds out that the old “location” is not being used anymore, will free the memory (garbage collection), else it will keep it until is needed.

(side note: in some languages you have to manually free the memory yourself, thanks JS engine!!)

So when you do

snowi = { ... }
mimi = snowi

// translate to pointing to the same address
snowi = <#0001>
mimi = <#0001>

-- later
snowi = null

// only change the address fpr snowi
snowi = <#0003>
mimi = <#0001> // still pointing to the same address

The JS engine will keep a reference to <#0001> since it's still used by mimi`.


Note: the reality is more complex than this, but this should suffice to illustrate the point…I hope.

:smile:

3 Likes

Ah, I see. Thank you, your explanation is good and clear! :smile: I’ll go ahead and read more on this subject.