1

I found this question in the h5bp/Front-end-Developer-Interview-Questions repository.

One example confused me.

var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
// foo.x is undefined  /* WHY??? */
bar.y = bar;  // This works however.
bar.y.y.y;
//> Object {n: 1, x: Object, y: Object}
var xoxo = foo = {n: 2};
//> Object {n: 2}

With bar, I assigned the object literal's x property to the object itself and what appears to be happening now, is that it's referencing itself through x "infinite times".

I expected the same behaviour from the line foo.x = foo = {n: 2};. What happens with foo.x and why? If you explained the steps that will get me to the right answer, I'd appreciate it

Wanted to see if there is a flaw in my right-hand assignment logic, but xoxo seems to be assigned as I expected.

Vince Varga
  • 6,101
  • 6
  • 43
  • 60
  • Strange! I always believed javascript did right hand assignment a = (b = (c = 1)). I want to know the reason too. – mehulmpt Mar 04 '17 at 19:20
  • Haha, I, too, was thinking along the lines of right-hand assignment, but it's clearly not what happens – Vince Varga Mar 04 '17 at 19:22
  • I believe it does happen, but something's goofy with objects – mehulmpt Mar 04 '17 at 19:23
  • 7
    Possible duplicate of http://stackoverflow.com/questions/32342809/javascript-code-trick-whats-the-value-of-foo-x – Omri Aharon Mar 04 '17 at 19:25
  • 3
    Possible duplicate of [Javascript code trick :What's the value of foo.x](http://stackoverflow.com/questions/32342809/javascript-code-trick-whats-the-value-of-foo-x) – gyre Mar 04 '17 at 19:30
  • The mechanism behind this is very well described in Chapter 1 "What is scope ?" of Kyle Simpson's book "Scope & Closures" from the "You Don't Know Js" book series – Nelson Teixeira Mar 04 '17 at 19:37
  • Thanks. I was looking for the question as I suspected it would cause headache for other people, too, but I didn't find it. – Vince Varga Mar 04 '17 at 22:51

0 Answers0