Search code examples
javascriptobjectpass-by-reference

reassigning javascript objects


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}

Solution

  • 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}