2

If javascript objects are assign by reference, shouldn't the second console.log show that obj2 = {c:3}

let obj1 = {a:1}
let obj2 = {b:2}

obj2 = obj1
console.log(obj2) // {a:1}

obj1 = {c:3}
console.log(obj2)  // still {a:1}
Eric Grossman
  • 219
  • 1
  • 4
  • 9
  • 1
    No, changing what `obj1` points to doesn't magically change what `obj2` points to, and the last edit to `obj2` made it point to the same thing as `obj1` at the time of the assignment, which was `{ a: 1 }`. – ASDFGerte Oct 25 '19 at 01:59

2 Answers2

1

So first you have this (both references pointing to the same object):

obj1 => {a:1} <= obj2

When you do obj1 = {c:3}, you do 2 things:

  • sever the connection obj1 =x=> {a:1}
  • create a new connection obj1 => {c:3}

Note that obj2 is unchanged (still pointing to the same thing): obj2 => {a:1}

So console.log(obj2) SHOULD still be = {a:1}

shafeen
  • 2,431
  • 18
  • 23
0

In short, variables references changed, but not memory address:

enter image description here

polunzh
  • 318
  • 2
  • 11