0

If I have a simple reference to an object as in the first example, the way I understand it is x.a and y.a point to the same address which holds the value 1. When I change the value at that address to 2, the value changes in both x and y.

But in the second example, I use Object.assign to create y. x and y are different references, but x.a and y.a both point to the same address. So why is it that when I change x.a, y.a is not changed in this case?

// simple reference
var x = {a:1};
var y = x;
console.log(x === y); // true
console.log(x.a === y.a) // true
x.a = 2;
console.log(y.a); // 2

console.log('end first example');

// same example but with Oject.assign
var x = {a:1};
var y = Object.assign({}, x);
console.log(x === y); // false
console.log(x.a === y.a); // true, x.a and y.a point to the same address
x.a = 2;
console.log(y.a); // 1, I was expecting this to be 2
radek79
  • 43
  • 9
  • 2
    In the first example `y` points to the same as `x` does. In the second the values happen to be the same (they're not "shared"). Both `x.a` and `y.a` have the value `2`. – evolutionxbox Jan 24 '22 at 00:28
  • 1
    [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) values are not assigned by reference – pilchard Jan 24 '22 at 00:32
  • `x = { a: { b: 2 } }; y = Object.assign({}, x); x.a.b = 1;` will show you a result similar to what you're expecting. See also [There is no "pass by reference" available in JavaScript](https://stackoverflow.com/a/7744623/989920) – evolutionxbox Jan 24 '22 at 00:32
  • 1
    or even simpler: `x = { a: 2 }; y = {a:2};` the `x.a == y.a` will be `true`; Demonstrates the _primitive values_ are compared. – Randy Casburn Jan 24 '22 at 00:37
  • @RandyCasburn this makes sense. So let me see if I got this right. In the second example x.a === y.a is true because we are comparing primitives. x.a === y.a is also true because we are comparing primitives, (check my understanding on this) even though the x.a and y.a happen to point to the same address. So in both cases '===' compares primitives, even though in the first example, the addresses of x.a and y.a are the same , but in the second example they are not. How do you then check if a reference is the same as another, without doing these kinds of examples and checking if values change? – radek79 Jan 24 '22 at 01:29
  • Perhaps you are looking for [Object.is()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) – Randy Casburn Jan 24 '22 at 02:58
  • @RandyCasburn, I did and save for some obscure math, it's the same as '===' – radek79 Jan 25 '22 at 01:08

0 Answers0