0

Consider this code:

let obj1 = {foo : 'bar'}
let obj2 = obj1

obj2.foo = 'asd'
console.log(obj1)   // { foo: "asd" }

obj2 = null
console.log(obj1)   // expected null, instead got { foo: "asd" }

If I understand right, when it comes to objects, by let obj2 = obj1 javascript does not actually create a new object, but references the same place in memory, hence the result of first log.

But, if obj2 is set to null, it actually leaves original object intact. How is this possible? I mean, I would expect either to be able to modify obj1 via obj2, or not. What causes this apparently selective behaviour? Thanks!

DBencz
  • 849
  • 1
  • 9
  • 15
  • 3
    `obj1` and `obj2` store a reference to the same object in memory. `obj2 = null` only overwrites that reference stored in `obj2` but doesn't modify or overwrite the referenced object – Andreas Oct 20 '20 at 08:44
  • 2
    The variable just holds the reference to the object. If you change the variable, it means it points to a different piece of data, doesn't modify the object. If you have two pieces of paper with my name on it, they both hold a reference to me. That's your variables. If you change one of the pieces of paper to say Brad Pitt, I don't suddenly turn into a Hollywood actor. You just have two pieces of paper referencing two different people. – VLAZ Oct 20 '20 at 08:46
  • VLAZ, I understand it is thin ice, but to follow up on your analogy, if it was your photo on both pictures, and, say, I drew a moustache on one, a moustache would appear on the other picture too. But if I erased one picture, the other would remain intact. And this is the part I don't understand... – DBencz Oct 20 '20 at 09:01
  • 1
    You do not erase the picture. Just the link to it. Check out [this one](https://stackoverflow.com/questions/742623/deleting-objects-in-javascript). – JavaScript Oct 20 '20 at 09:07
  • 2
    Basically you can only *delete* an object by removing all references to it (=gets garbage collected). You can not really delete the object straight up and let the other references lead to nothing. – JavaScript Oct 20 '20 at 09:10
  • 1
    @DBencz You're not following the analogy. If you have two pieces of paper with my name on it, then "drawing a moustache" would be analogous to going "I want to draw a moustache on the person identified by this piece of paper". Somebody (presumably whoever has the role of the JS engine) goes and does it. Now both pieces of paper still refer to me and if you follow the each of the references (look at who the piece of paper references) you'll see me with a moustache. The picture thing you change only works if they are completely separate things - not objects. – VLAZ Oct 20 '20 at 09:22

0 Answers0