By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,530 Members | 880 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,530 IT Pros & Developers. It's quick & easy.

Every function returns 10, why?

P: 2
Expand|Select|Wrap|Line Numbers
  1. function createFunctions() {
  2.     var result = new Array();
  3.  
  4.     for (var i = 0; i < 10; i++) {
  5.         result[i] = function () { return i; };
  6.     }
  7.  
  8.     return result;
  9. }
  10.  
Jul 29 '13 #1

✓ answered by Dormilich

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):
Expand|Select|Wrap|Line Numbers
  1. for (var i = 0; i < 10; i++) {
  2.   result.push(
  3.     // this is an IIFE (immediately invoked function expression) 
  4.     function (x) { 
  5.       // a Closure again, but not using loop variable i
  6.       return function() { return x; }
  7.     }(i)
  8.   );
  9. }

Share this Question
Share on Google+
1 Reply


Dormilich
Expert Mod 5K+
P: 8,639
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):
Expand|Select|Wrap|Line Numbers
  1. for (var i = 0; i < 10; i++) {
  2.   result.push(
  3.     // this is an IIFE (immediately invoked function expression) 
  4.     function (x) { 
  5.       // a Closure again, but not using loop variable i
  6.       return function() { return x; }
  7.     }(i)
  8.   );
  9. }
Jul 29 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.