Object references to undefined in javascript [closed]

If you have an object in javascript and it references another object and then 2nd object changes, you can expect to see the change in the referenced object. However, if the 2nd object is initially undefined, the first object will never reflect new changes. Can anyone potentially explain what is happening under the hood in this code?

//Here we see the reference updated
var myobj = {};
var pointer = myobj;
myobj.value = 1;

//Here if we start as undefined, create a reference and then allocate a new object - not so much    
var myobj = undefined;
var pointer = myobj;
myobj = {}
myobj.value = 1;

This is observed under

$ node --version 



The answer is pretty simple. You need to understand the difference between a value and reference type variables.

In the first example have a reference type variable i.e. myObj which points to an area in the memory. Then you define one more variable i.e. pointer that points to the same area. That's why any changes to one object is instantly reflected on the other.

In the second example things are slightly different. You define the myObj which is of Undefined type. Which means that there is no value specified for this variable. You would do that in the case where you have a value type variable e.g. Number, string etc. for which you don't have a value to assign; It also means that myObj doesn't point to any are in the heap section of the memory. Then when you do this var pointer = myobj; you're simply copying the value of one variable to the other; It's similar to doing this, for example: var pointer = 5; This is called copy by value' so that's why the changes are not reflected.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.