5

Can anyone explain me what is going on in this code below? Why does it work like this? I expected the variable a would change too...

var base = {
  cars: {
    color: "blue",
    brand: "Ford"
  }
}

var a = base.cars;
base.cars = function () { console.log("example method") }

console.log(base) // changed to method
console.log(a) // still is object - why?
FZs
  • 16,581
  • 13
  • 41
  • 50
Telirw
  • 373
  • 3
  • 15
  • 4
    It's not clear why you expected that. You're assigning a new value to the property, but that doesn't alter any of the other references to the old value. – jonrsharpe Feb 09 '20 at 22:01
  • You're confusing it with pointers wherein changing the value using a pointer would change all the other values referenced using that pointer. Here, a new object is created and the reference of base.cars is changed but that of a remains the same. – Gaurav Punjabi Feb 09 '20 at 22:04
  • I'm getting object object for the console logs. Are you saying you are *not* getting `object` as return result on `console.log(base)`. Im unable to reproduce your result using your exact code. – GetSet Feb 09 '20 at 22:05

1 Answers1

3

Because there are no pointers in JavaScript.


At the beginning, you have something like this:

base ---+
        |
        v
        {
          cars ----+
        }          |
                   v
                   {
                     color: "blue"
                     brand: "Ford"
                   }
                   ^
                   |
a -----------------+

Now both base.cars and a point to the same object.

Then, when you reassign base.cars, it becomes:

base ---+           
        |          
        v          
        {          
          cars ---> function(){ ... }
        }          
                   
                   {
                     color: "blue"
                     brand: "Ford"
                   }
                   ^
                   |
a -----------------+

a will continue to point at the object referenced by base.cars at the time of the assignment. Then, even when base.cars is reassigned, it doesn't affect the value (and the reference) of a.


If you were able to create a pointer, it would look like this:

base ---+
        |
        v
        {
          cars ----+
        } ^        |
          |        v
          |        {
          |          color: "blue"
          |          brand: "Ford"
          |        }
          |     
          |        
a --------+

...and after reassignment:

base ---+
        |
        v
        {
          cars ----> function(){ ... }
        } ^        
          |        
          |        {
          |          color: "blue"
          |          brand: "Ford"
          |        }
          |        |
          |        +--> Garbage collection
a --------+         
FZs
  • 16,581
  • 13
  • 41
  • 50