-1

So far I believed objects in javascript if assigned to another variable were always by reference.

For e.g

var x = {
    key1: "key1",
    key2: "key2"
}

var y = x

So if I do something like y.key1= "modifiedKey1"

values of key1 in x witll change too. x.key1 = modifiedKey1

however, when I do this, y = null or y= "someRandomString"

There is NO change in x

x is not null, it remains the same object.

What exactly is happening?

luk2302
  • 55,258
  • 23
  • 97
  • 137
ABGR
  • 4,631
  • 4
  • 27
  • 49
  • `y` is still a normal variable you can reassign. Once you change `y`, it loses all references to `x`. Compare `changing y` with `changing something inside y`. It's not the same thing. – Shilly Sep 27 '19 at 11:26

1 Answers1

0

Because you do set the reference to null meaning you no longer point anywhere, it does not affect the object it pointed to.
Same with y = {"a" : 3} - x will not change because you did not change the object y and x pointed to but you change what object y points to.

luk2302
  • 55,258
  • 23
  • 97
  • 137