0

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?

3
  • hi, sorry if it wasnt clear. its just to explain the mem[0] === obj line Commented Jul 18, 2022 at 20:43
  • I think you mean arr[0] === obj to keep the naming consistent (or const mem = [obj]; Commented Jul 18, 2022 at 20:44
  • 1
    true, forgot to change it as i was copying from my console :) Commented Jul 18, 2022 at 20:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.