473,770 Members | 5,299 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Every function returns 10, why?

2 New Member
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
1 1385
Dormilich
8,658 Recognized Expert Moderator Expert
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
2207
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 "include". There are two functions written in this included file: ===========================================================================
8
1702
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, $min, $max) { $length = strlen ($string); if (($length < $min) || ($length > $max)) {
11
18331
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 VBScript runtime error '800a000d' Type mismatch: 'formatNumber'
4
11360
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 function ? Thank You. Octavio and.c:15: attention : type mismatch with previous implicit declaration and.c:11: attention : previous implicit declaration of `fb'
18
3136
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 how global variables and function returns work... For example, I have a global array "char datestring;" which is defined in the function speakdate. speakdate just converts a set of integers (date variables) to a string.
4
2754
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 = get_network_info (strIpAddress, &strHostname, &nPortNumber) where this fictitious function returns a status, but also returns modified values for a hostname and a port number. In Python, there does not seem to be an easy way to have functions return...
0
1195
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'> Remembering c_void = c_int from K&R C often works, but if you say a restype is c_int, then doctest's of that call will print an int, yuck. If you say the restype is None, then those doctest's work: they print
0
1141
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 just pointlessly annoying. Hope this helps (and of course I trust you'll dispute if I'm nuts),
5
2641
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 (function() == '/0'). But then I see that the those if statements are flagging true when the function returns back a char * or no length
2
1071
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 function which should return like this return (stuffedname,bigstring, numbertimes,num_times_search_string) this is the variable that calls the functions. when a function returns something AND there is a variable set as shown immediately below,...
0
9591
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10225
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8880
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7415
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6676
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3969
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.