2

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;
console.log(pointer.value);

//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;
console.log(pointer.value);

This is observed under

$ node --version 
v0.8.22
1
  • 1
    your first example does not work the way you describe - you created first object (it does not have value property), assigned it to pointer, and then created the second object with value - pointer.value is undefined Commented Feb 26, 2014 at 14:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.