January 30, 2015 · javascript

Javascript's object mutability

When we have two numbers, 120 and 120, we can consider them precisely the same number, whether or not they refer to the same physical bits. But with objects, there is a difference between having two references to the same object and having two different objects that contain the same properties. Consider the following code:

var object1 = {value: 10};  
var object2 = object1;  
var object3 = {value: 10};

console.log(object1 == object2);  
// → true
console.log(object1 == object3);  
// → false

object1.value = 15;  
// → 15
// → 10

The object1 and object2 variables grasp the same object, which is why changing object1 also changes the value of object2. The variable object3 points to a different object, which initially contains the same properties as object1 but lives a separate life.

JavaScript’s == operator, when comparing objects, will return true only if both objects are precisely the same value. Comparing different objects will return false, even if they have identical contents. There is no “deep” comparison operation built into JavaScript, which looks at object’s contents, but it is possible to write it yourself (which will be one of the exercises at the end of this chapter).

Source: http://eloquentjavascript.net/04_data.html

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus