title: Why is this primitive variable being passed to a function by reference instead of by value?
body: <p>This involves some Angular but I think it is mostly a pure javascript scope question.  I have a directive that is invoked a couple times on my page with an <code>ng-repeat</code>.  When it is first invoked, I set the variable <code>current_index</code> equal to the index number of the tag on the unit page like so:</p>
  
  <pre><code>var current_index = scope.$eval(attrs.index);
  </code></pre>
  
  <p>I then pass it to a function that is on a half second delay.   </p>
  
  <pre><code>    g.append("g")
      .transition()
      .duration(500) //Half second delay
      .on("start", function(){
        tick(current_index);  //Passing the current_index variable
      });
  </code></pre>
  
  <p>However, by the time this function is called for each instance of the tag, <code>current_index</code> is always equal to the number of the last index that was invoked (Ex: If I have 3 tags corresponding to my directive, and print <code>console.log(current_index);</code>  in my function that's on a delay, it will print <code>2</code> 3 times, rather than <code>0, 1, 2</code>.  </p>
  
  <pre><code>function tick(index){
        console.log(index);
      }
   // Prints 2, 2, 2
  </code></pre>
  
  <p>However, if I introduce a new variable, <code>a</code>, and set it equal to <code>current_index</code>, and pass THAT into the function it works as expected. </p>
  
  <pre><code>var current_index = scope.$eval(attrs.index);
  var a = current_index
  
  g.append("g")
  .transition()
  .duration(500) //Half second delay
  .on("start", function(){
    tick(a);  //Passing the a variable
  });
  
  
  function tick(index){
        console.log(index);
      }
   // Prints 0, 1, 2
  </code></pre>
  
  <p>It would seem that <code>current_index</code> is being passed as an object, and <code>a</code> is being passed as a primitive, but both return <code>number</code> when I do the <code>typeof</code> function.  What's going on here?</p>