title: JavaScript code trick: What's the value of foo.x
body: <p>I found this problem in a GitHub front-end interview questions collection:</p>
  <blockquote>
  <pre><code>var foo = {n: 1};
  var bar = foo;
  foo.x = foo = {n: 2};
  </code></pre>
  <p>Question: What is the value of foo.x?</p>
  </blockquote>
  <p>The answer is <code>undefined</code>.</p>
  <p>I've done some research and what I understand this problem is (correct me if I'm wrong):</p>
  <ul>
  <li><code>var foo = {n: 1};</code> declares an object <code>foo</code> which has property <code>n</code> equal to 1.</li>
  <li><code>var bar = foo;</code> declares an object <code>bar</code> which refers to the same object as <code>foo</code>.</li>
  <li><code>foo.x = foo = {n: 2};</code> which I believe is equal to <code>foo.x = (foo = {n: 2});</code></li>
  <li>And then I got <code>foo.x</code> equals to <code>undefined</code>. However, the value of <code>bar.x</code> is the object <code>{n:2}</code>.</li>
  </ul>
  <p>If <code>bar</code> and <code>foo</code> refer to same object, why did <code>bar.x</code> get a value while <code>foo.x</code> is <code>undefined</code>? What is really happening in <code>foo.x = foo = {n: 2};</code>?</p>