0

I'm not sure why I'm getting an error on the following snippet (adapted from JavaScript closure inside loops – simple practical example):

var funcs = {};
for (var i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = (function(n) {            // and store them in funcs
        console.log("My value: " + n); // each should log its value.
    })(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

It seems like this should run ok; I know this is just something I don't fully get.

Here is the errror I get: enter image description here

thx for any help

Community
  • 1
  • 1
timpone
  • 19,235
  • 36
  • 121
  • 211

1 Answers1

2

You need to return a function, rather than a result of the function. Try:

funcs[i] = (function(n) {
  return function() { 
    console.log("My value: " + n); 
  }
})(i);

Example:

> var funcs = {};
for (var i = 0; i < 3; i++) {
  funcs[i] = (function(n) { 
    return function() {console.log("My value: " + n);} 
  })(i);
}
for (var j = 0; j < 3; j++) {
  funcs[j]();                
}
My value: 0
My value: 1
My value: 2
mishik
  • 9,973
  • 9
  • 45
  • 67