0

I have a problem understanding reference assignments in JS.

var foo = { n: 1 };
var bar = foo;

bar.n = 3;

console.log(foo.n);
console.log(bar.n);

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

console.log(foo.n);
console.log(foo.x);
console.log(foo.x.n);

I expected the last 2 console logs to be:

console.log(foo.x); // Javascript object {n: 2}
console.log(foo.x.n); // 2

but the actual output is undefined and execution error respectively.

Andreas
  • 21,535
  • 7
  • 47
  • 56
Tyiliyra
  • 359
  • 3
  • 14
  • 1
    Tell us what you think `foo.x = foo = {n: 2};` does and why you are writing it that way – charlietfl Jul 27 '19 at 12:05
  • Right. this will just assign that object to both foo.x and foo. – Ravi Jul 27 '19 at 12:09
  • So the '=' operator is right-sided. Therefore first foo = {n: 2} is executed, so foo.n property becomes 2? Then foo.x should be assigned the result of the (foo = {n: 2}) expression, which I thought would be foo's Javascript object reference? – Tyiliyra Jul 27 '19 at 12:10
  • 2
    Possible duplicate of [Javascript code trick :What's the value of foo.x](https://stackoverflow.com/questions/32342809/javascript-code-trick-whats-the-value-of-foo-x) and [Why is the value of foo.x undefined in foo.x = foo = {n: 2}?](https://stackoverflow.com/questions/34933210) and [Multiple left-hand assignment with JavaScript, really right associative?](https://stackoverflow.com/questions/34371980) and [Assignment associativity](https://stackoverflow.com/questions/37763113) – adiga Jul 27 '19 at 12:13
  • @adiga—yes, lot of dupes. :-) – RobG Jul 27 '19 at 12:14
  • It might help if you do `console.log(bar)` to find the missing *x* property. ;-) i.e. the object initially referenced by *foo* (and also referenced by *bar*) gets the *x* property, but now *foo* references a different object. – RobG Jul 27 '19 at 12:18

1 Answers1

1

your one-line assignment like this

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

caused that foo got reference to { n: 2 } erasing the previous definition with x property, so when you try to print console.log(foo.x); it prints undefined