-1

I am trying to understand the following

        var obj1 = {
            value: "first value"
        };

        var obj2 = {
            value: "second value"
        };

        var  obj3 = obj2;

        function change(obj1, obj2) {
            obj1.value = "asdasd";
            obj2 = "lol";
        }

        change(obj1, obj2);

        console.log("1",obj1.value);//"asdasd"
        console.log("2",obj2.value);//"secondvalue"

why only obj1.value is changed ??

Sai Ram
  • 4,196
  • 4
  • 26
  • 39

1 Answers1

0

When you change the parameter obj2 to point to a string, you loose the reference to the object you passed to it.

     function change(obj1, obj2) {
        obj1.value = "asdasd";
        // You are only changing the parameter obj2 not a sub property of the object it contained.
        obj2 = "lol";
    }
Alexandre Borela
  • 1,576
  • 13
  • 21