2

I have this kind of construction

let a = {x: 1}
let b = a
a.x = a = {y: 2}

How you can explain in details how I get these results ?

a.x = undefined
a={y: 2}
b={x: {y: 2}}
Manuk Karapetyan
  • 534
  • 4
  • 19
  • You've just overriden `a` with an object that only contains the property `y`. `a = {y: 2}` - You can see this when you console.log `a.y`. These assignments are done right to left. – Lewis Apr 04 '19 at 12:57
  • `a.x` is evaluated (but not yet written) before `a = {y:2}` – Bergi Apr 04 '19 at 13:00
  • The very last assignment that occurs here is `a = { y: 2 };`. This clobbers `a.x`. Perhaps you were expecting the opposite order of assignments on the last line? – Gershom Maes Apr 04 '19 at 13:00
  • @Lewis you just explain me only one case. I understand why this happens , but I can't explain it to others in clear way ) – Manuk Karapetyan Apr 04 '19 at 13:04
  • @Manuk it might be a small example, but there's a surprising amount of stuff happening here (as you understand). Someone will post a more in depth answer, I'm sure. – Lewis Apr 04 '19 at 13:06
  • 1
    This has useful answers on the order: [Why do these snippets of JavaScript behave differently even though they both encounter an error?](https://stackoverflow.com/questions/54646467) – adiga Apr 04 '19 at 13:06

0 Answers0