p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Professional JavaScript for Web Developers 2nd edition ISBN: 9780470227800 (http://p2p.wrox.com/forumdisplay.php?f=475)
-   -   Chapter 7 Closures and Variables Question (http://p2p.wrox.com/showthread.php?t=80217)

Mikeos July 22nd, 2010 07:39 AM

Chapter 7 Closures and Variables Question
On page 188 there is the following code:

function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(){
return i;
return result;

The explanation paragraph that follows is confusing, it states the following:

'This function returns an array of functions. It seems that each function should just return the value of its index, so the function in position 0 returns, the function in position 1 returns 1, and so on. In reality, every function returns 10.'

The first part makes sense in that the function returns an array of functions, but as far as each index holding 10 is concerned it doesn't actually hold do that. I tried calling the function to see what value each actually holds like so:

var theResult = createFunctions();

The value you get is the actual function itself for each index not the value of 10 for each index that is allegedly supposed to be return, I tried running the eval() method on the theResult variable instead but the result was the same. So what is actually going on? Have I missed something here?

Also with the so called solution to the problem the same thing happens, solution in book as follows:

function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(num){
return function(){
return num;
return result;

Also how is num actually getting the i variable, is it due to the line }(i); as that is the final variable within the enclosure of the containing function?
Finally how is the the anonymous function being called immediately as stated in the book, what line is actually calling it?

The book so far has been excellent but this specific section of closures and variables has confused the heck out of me.

Please help.


nzakas July 22nd, 2010 06:32 PM

Hi Mike,

You're testing the result incorrectly. The way you should be testing it is:

var functions = createFunctions();

alert(functions[0]());  //10
alert(functions[1]());  //10


What you're doing is just alerting the array of functions, which will appear to be the same in both cases.

To answer your other questions: i is passed to num via (i). The anonymous function is being immediately called by placing parentheses at the end. i is the value being passed into the function and num is the name of the argument for that function.

Mikeos July 28th, 2010 05:26 PM

Excellent stuff, problem solved, thanks!!!

All times are GMT -4. The time now is 09:43 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.