title: Javascript pointer/reference craziness. Can someone explain this?
body: <p>Javascript passes objects by reference. This makes perfect sense. But once you start manipulating those objects, everything acts in a way that seem unintuitive. Let me offer an example:</p>
  
  <pre><code>var a, b;
  
  a = {}
  b = a;
  a['one'] = {};
  
  console.log( JSON.stringify(a) );
  // outputs: {"one":{}}
  
  console.log( JSON.stringify(b) );
  // outputs: {"one":{}}
  </code></pre>
  
  <p>This is all well and good because now <code>b</code> has a pointer to <code>a</code> so it's expected that assigning stuff to <code>a</code> will also affect <code>b</code>.</p>
  
  <p>But then if I do this:</p>
  
  <pre><code>a = a['one'];
  
  console.log( JSON.stringify(a) );
  // outputs: {}
  
  console.log( JSON.stringify(b) );
  // outputs: {"one":{}}
  </code></pre>
  
  <p>This is surprising to me. I'd expect <code>a</code> and <code>b</code> to still be the same (and to be <code>{}</code> since <code>a['one']</code> was previously set to <code>{}</code> and <code>a</code> was set to <code>a['one']</code>).</p>
  
  <p>But that's not the case. It appears that <code>a</code> loses its reference to <code>b</code> when it's assigned to something new, but <code>b</code> maintains the value that <code>a</code> was set to prior to <code>a</code> loosing its reference to <code>b</code>.</p>
  
  <p>But then if I do this:</p>
  
  <pre><code>a['two'] = 2;
  
  console.log( JSON.stringify(a) );
  // outputs: {"two":2}
  
  console.log( JSON.stringify(b) );
  // outputs: {"one":{"two":2}}
  </code></pre>
  
  <p>What? <code>a</code> has clearly lost it's reference to <code>b</code>, but <code>b</code> seems to still have some reference to <code>a</code>.</p>
  
  <p>Does the empty object <code>{}</code> point to some place in memory so every variable referencing it is now pointing to the same place?</p>
  
  <p>Can someone with a firm grasp on this explain it to me?</p>