Every function returns 10, why?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • omryk78
    New Member
    • Jul 2013
    • 2

    Every function returns 10, why?

    Code:
    function createFunctions() {
        var result = new Array();
    
        for (var i = 0; i < 10; i++) {
            result[i] = function () { return i; };
        }
    
        return result;
    }
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    Every function returns 10, why?
    because of the Closure on line #5.

    since JavaScript has function scope, each function block (line #1, #5) has access to its own variables and the variables of any parent scope (function createFunctions () to window, the anonymous function to createFunctions () and window). if a variable from a parent/outer scope is used in the (inner) function, the value is enclosed/retained in the function, even if the function body is left by the parser (and it is used the variable’s value at run-time(!), not at "compile"-time). and since your variable (i) is set to 10 when the outer function is left, the closured variables all have the last value of i (i.e. 10).

    to get around that you have to break the closure (often by using an IIFE):
    Code:
    for (var i = 0; i < 10; i++) {
      result.push(
        // this is an IIFE (immediately invoked function expression) 
        function (x) { 
          // a Closure again, but not using loop variable i
          return function() { return x; }
        }(i)
      );
    }

    Comment

    Working...