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?
CodePudding user response:
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.
CodePudding user response:
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