3

I saw this somewhat strange assignment operator chaining somewhere and I've been trying to understand how this is possible, but I seem unable to wrap my head around it.

var a = {n: 1};

var b = a;  

a.x = a = {n: 2};

console.log(a.x); // undefined  
console.log(b.x); // {n: 2}
David Blay
  • 527
  • 1
  • 3
  • 14

2 Answers2

4

The internal reference value for a.x — the "target" of the assignment a.x = a — is calculated before the assignments happen. The target of the assignment is therefore the "x" property on the old value of a, which is the same as b. The new value of a doesn't have an "x" property, so that's undefined. However, the assignment gave an "x" property to the old value of a, which is the current value of b.

If you like "language lawyering", you can see a description here in the ES2015 spec for the = operator and how it works. Note that in step 1, something called lref is determined. That's the "target" I mentioned in the above paragraph, and note that it happens before the right-hand "assignment expression" is computed.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1
var a = {n: 1};

var b = a;   // since a is an object b holds the reference of 

a.x = a = {n: 2};
  • a = {n : 2} this changes the value of a, so as the memory reference is changed due to assignment

  • a.x = a a now points to new memory reference whereas a.x still refer to old reference ( as it is evaluated before right hand side expression )

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 2
    But `b.x` is *not* `undefined`. – Pointy Aug 07 '19 at 18:55
  • @Pointy can you please explain a bit where i am getting it wrong ? would love to correct myself – Code Maniac Aug 07 '19 at 19:05
  • 1
    The key is that in `a.x = a = {n: 2}` the *lref* `a.x` is computed *before* the right hand side of the leftmost `=` is computed. Thus the "memory location" for the right hand side of that, where `a` changes, happens before `a` changes. Thus even though it still says `a.x` it's effectively referring to `b.x` because be is the only remaining reference to the *old* value of `a`. – Pointy Aug 07 '19 at 19:11
  • @Pointy oh makes sense, thanks for info learnt something new :) – Code Maniac Aug 07 '19 at 19:14