3

Today I came across this problem in javascript and do not know why it happens.

var a = {
    prop: {
        bool: true
    }
};

console.log(a.prop.bool); // logs true
var b = a;
b.prop.bool = false;
console.log(a.prop.bool); // logs false ¿?
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Datamosh
  • 126
  • 1
  • 7
  • -1: You tagged it as "reference" so you clearly knew at least something about it. Searching the web for "javascript variable reference" provides lots of explanations... so the question doesn't show research effort. – Chris Morgan Oct 06 '11 at 23:42
  • 1
    Sorry, I really looked for the answer but did not find an answer as accurate as I got. – Datamosh Oct 06 '11 at 23:49

3 Answers3

5

The expression { prop: ... } expression is evaluated once to create one object.

a and b both are references to that single object.

See What's the difference between passing by reference vs. passing by value? and http://en.wikipedia.org/wiki/Reference_(computer_science)

References are widely used in programming, especially to efficiently pass large or mutable data as arguments to procedures, or to share such data among various uses.

EDIT

clone from underscore does a shallow copy.

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

To create a deep copy, the easiest way is probably to serialize and deserialize. This will do weird things if a has reference cycles though.

var b = JSON.parse(JSON.stringify(a));
Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
5

You've created a reference to the same object. When you do this, any changes of variable b will affect the object stored in variable a.

You will need to do a 'clone' of the object to change it so you have two objects instead of one with two references.

Freesnöw
  • 30,619
  • 30
  • 89
  • 138
3

when you assign b to a the assignment is by reference meaning b references the same location in memory as a so when b is updated and you observe a it looks like a is also updated.

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46