0

I was trying to understand some javascript and found some quite unexpected behavior. Not knowing much about this language I wanted to find out what this behavior is called so that I can read about it formally.

Here's an example of the behavior:

var test={'x':2};

var test2=test;

test2.sourceLinks = [];

console.log('test',test);
console.log('test2',test2);

To my amazement, I found that modifying the 2nd variable somehow modifies the first as well. The variable "test" will also have an attribute .sourceLinks = []. Do I understand what's happening correctly, and if so, what's the formal term for this behavior?

I found that the answer to this is covered in How do I correctly clone a JavaScript object? after I posted it, although that covered more than I was asking about.

Community
  • 1
  • 1
ouonomos
  • 700
  • 1
  • 9
  • 25
  • possible duplicate of [Most elegant way to clone a JavaScript object](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object) – Paul Aug 16 '15 at 03:58

3 Answers3

3

Behavior is called creating a reference. When variable assigned is an object actually it is not copied, rather the result of assignment is a new reference (pointer) to the object.

This doesn't happen with primitive types:

  • number,
  • string,
  • boolean,
  • null,
  • undefined.

But happens with all object types:

  • object,
  • Array,
  • function.

This difference is significant in javascript. When some value should be passed to another scope and it might be modified there it should be passed be reference.

function main(){
    var x = 1;
    modify(x);
    console.log(x);//x remains 1
}
function modify(arg){
    arg = 10;
}

Whereas when it is passed as a field of an object, it can be modified via reference to an object:

function main(){
    var o = {x : 1};
    modifyObj(o);
    console.log(o);//o.x now equals 10
}
function modifyObj(arg){
    arg.x = 10;
}
Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38
2

It's holding the reference.

When you assign object/array/function to another object/array/function it'll assign reference instead of value.

To overcome this you have to clone it

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • Thanks for responding. SO let me know that this is a duplicate question, but I will try to credit you as you were the first to respond. In my case, the duplicating behavior is desired so no need to clone. – ouonomos Aug 16 '15 at 05:24
0

When declaring a variable in Javascript you are creating an object in memory and the variable in the scope is a pointer to that memory object.

In your example both variables (test and test2) are pointing to the same object. Hence, when you modify the the either variable pointer, it is modifying the same object in memory.

pstricker
  • 692
  • 2
  • 5
  • 16