Potato
Potato

Reputation: 21

Object inside an array keep the old obj reference after changing obj value

could someone please explain me this:

let obj = {name: 'puki'}
const arr = [obj]
arr[0] === obj // true (same ref address)
obj = null
console.log(arr) // [{name: 'puki'}]

how come the array is keeping the old obj ref?

Upvotes: 0

Views: 48

Answers (2)

IT goldman
IT goldman

Reputation: 19485

In other words, you are not deleting the object, but rather the pointer to it. Object variables are actually pointers to the object itself. So that's why you can have many pointers to same object. Each will affect it. But removing a pointer doesn't remove the object unless it's the final pointer to it.

Upvotes: 1

Voided Name
Voided Name

Reputation: 128

You are confusing an object reference and the object itself.

In your code obj is a reference (an address) to the actual object {name: 'puki'}

The array also stores the reference (the address) to the actual object.

When you overwrite the reference obj with null you're not actually modifying the actual object {name: 'puki'} or the target of the address, you're just overwriting the reference (pointer) with the null pointer / value. There is no dereferencing in Javascript like it exists in C / C++

Upvotes: 0

Related Questions