Javascript closure – binding value instead of reference

The below example was taken from the book, “Javascript: The good parts”. The author says that the helper function returns a function that binds to the current value of var i.

Can anyone explain what makes it to bind the VALUE instead of REFERENCE of var i, because helper function is a closure to add_the_handler function and should only see the reference of var i:

  • Does this qualify as a Javascript closure?
  • Setting a variable in the closure scope
  • JavaScript closure and the this object
  • accessing mutable variable in an event closure
  • Javascript - setTimeout Closure Issue
  • JavaScript: How to return an outer function inside an asynchronous inner function?
  • var add_the_handlers = function (nodes) {
       var helper = function (i) {
          return function (e) {
            alert(i);
          };
        };
        var i;
        for (i = 0; i < nodes.length; i += 1) {
           nodes[i].onclick = helper(i);
        }
    };
    

  • how to change local functions of highcharts
  • Is this a valid use case for javascript closure?
  • Passing variable in parent scope to callback function
  • Please explain closures, or binding the loop counter to the function scope
  • Is it possible to gain access to the closure of a function?
  • Javascript - can't understand closure
  • 3 Solutions collect form web for “Javascript closure – binding value instead of reference”

    If you were to say:

    nodes[i].onclick = function(){ alert(i) };
    

    The function would not have it’s own copy of i because i is not declared within the scope of the function.

    To help you see this better I’ve modified your above code:

    var add_the_handlers = function (nodes) {
        var helper = function(t) {
          // t is in the scope of "helper"
          return function(e){
            // e is in the scope of this anonymous function
            // and is not used
            alert(t);
          };
        };
    
        // Variables declared here are in the scope of "add_the_handlers"
        var i;
        for (i = 0; i < nodes.length; i += 1) {
           nodes[i].onclick = helper(i);
        }
    };
    

    In the “real world” you’ll often see code like the above shortened to look like this:

    var add_the_handlers = function(nodes){
        var i;
        for(i = 0; i < nodes.length; i++)
           nodes[i].onclick = (function(i){ return function(e){ alert(i); }; })(i);
    };
    

    You pass the current value of i into the function helper. Inside that function the variable i, a (confusingly named) parameter to the function, is different from any other i. The closure returned thus binds to that particular i (really the [[scope]] which contains that i, but…).

    Happy coding.

    This is a guess: i is a primitive, so it’s always accessed by value, and not by reference.