473,386 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Every function returns 10, why?

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. }

1 1375
Dormilich
8,658 Expert Mod 8TB
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

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

Similar topics

7
by: knoak | last post by:
Hi there, I have a site with just a few pages. (e.g. home.php) In every page there is another page included with things like the header etc. The included file is in a subdirectory called...
8
by: varois83 | last post by:
Hi I am a newbie and struggling with my guestbook validation process. I have found the following function online to check the length of a form field. <?php function checkLength($string,...
11
by: eddie wang | last post by:
The following code with formatnumber function returns me the following code. Why? Thanks. <td align="right"><Font class=content4><%=formatNumber(ars.Fields("SOLD_AMOUNT"),2)%></td> Microsoft...
4
by: octavio | last post by:
Hello members of the comp.lang.c newsgroup. Please I need you help on the following one. Compiling the simple code I'm getting this error message. Why ? Please what's the correct type of the fb...
18
by: ben.carbery | last post by:
Hi, I have just written a simple program to get me started in C that calculates the number of days since your birthdate. One thing that confuses me about the program (even though it works) is...
4
by: Michael Yanowitz | last post by:
I am still new to Python but have used it for the last 2+ months. One thing I'm still not used to is that functions parameters can't change as expected. For example in C, I can have status =...
0
by: p.lavarre | last post by:
Now at http://pyfaq.infogami.com/suggest we have: FAQ: How do I declare that CTypes function returns void? A: c_void = None is not doc'ed, but is suggested by: <class 'ctypes.c_void_p'> ...
0
by: p.lavarre | last post by:
Now at http://pyfaq.infogami.com/suggest we have: FAQ: How do I declare that a CTypes function returns unsigned char? A: c_uchar = ctypes.c_ubyte This irregularity actually is doc'ed, it's...
5
by: Travis | last post by:
I am using a function that returns a const char * that is usually a word, etc. How can I check to see if what it returns is empty? I tried if (function() == "") and (function() == NULL) and...
2
by: davidj411 | last post by:
if you run execfile function to run a python script and that script has variables and functions, should't those variable change in the interactive prompt too? script snippet that calls the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.