Search code examples
javascriptpass-by-referencepass-by-value

In javascript how does the below code works


In Javascript how does the below code works.

var a = {
  prop1: "a",
  prop2: "b",
  fun: function() {
    return this.prop1 + " " + this.prop2;
  }

}
var a2 = a;
a.fn = "v";
a = {};
if (a === a2) {
  console.log(true);
} else {
  console.log(false);
}

The above code prints false.

But if I comment out the line a={} the value which prints on console is true.

var a = {
  prop1: "a",
  prop2: "b",
  fun: function() {
    return this.prop1 + " " + this.prop2;
  }

}
var a2 = a;
a.fn = "v";
//a={};
if (a === a2) {
  console.log(true);
} else {
  console.log(false);
}

How the above code works, as Both variables(a and a2) points to the same object but when I initialized a with {} it gave false.


Solution

  • ...as Both variables(a and a2) points to the same object ...

    They don't anymore, as of this line:

    a={};
    

    At that point, a2 refers to the old object, and a refers to a new, different object.

    a2 = a doesn't create any kind of ongoing link between the variable a2 and the variable a.

    Let's throw some Unicode-art at it:

    After this code runs:

    var a = {
      prop1: "a",
      prop2: "b",
      fun: function() {
        return this.prop1 + " " + this.prop2;
      }
    
    }
    var a2 = a;
    a.fn = "v";
    

    At this point, you have something like this in memory (with various details omitted):

    a:Ref44512−−−+
                 |
                 |
                 |    +−−−−−−−−−−−−−+                 
                 +−−−>|  (object)   |                 
                 |    +−−−−−−−−−−−−−+                 
                 |    | prop1: "a"  |                 
                 |    | prop2: "b"  |   +−−−−−−−−−−−−+
    a2:Ref44512−−+    | fun:Ref7846 |−−>| (function) |
                      | vn: "v"     |   +−−−−−−−−−−−−+
                      +−−−−−−−−−−−−−+                 
    

    Those "Ref" values are object references. (We never actually see their values, those values are just made up nonsense.) Notice that the value in a and the value in a2 is the same, however.

    If you do a === a2 at this point, it will be true: Both variables refer to the same object.

    But when you do this:

    a={};
    
                      +−−−−−−−−−−−−−+
    a:Ref84521−−−−−−−>|  (object)   |
                      +−−−−−−−−−−−−−+
    
                      +−−−−−−−−−−−−−+                 
    a2:Ref44512−−−−−−>|  (object)   |                 
                      +−−−−−−−−−−−−−+                 
                      | prop1: "a"  |                 
                      | prop2: "b"  |   +−−−−−−−−−−−−+
                      | fun:Ref7846 |−−>| (function) |
                      | vn: "v"     |   +−−−−−−−−−−−−+
                      +−−−−−−−−−−−−−+                 
    

    At this point, a === a2 is false: The variables refer different objects.