Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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++

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading