0

Following is the program I am trying-

function getNumFunc() {
  var numbers = [];
  var i = 0;  
  for (; i < 10; i++) {    
    numbers[i] = function(){
      return i;
    };
  }
  return numbers;
}

var myNumArr = getNumFunc();
console.log(myNumArr[5]());

Expected Output - 5

I found/read that its a case of IIFE http://javascriptissexy.com/understand-javascript-closures-with-ease/

I tried, but its not working ..let me know what I am doing wrong.

I passing i like this but it is making my function erroneous.

Tried -

numbers[i] = function(j){
 return function(){
   return j;
 }();
}(i);
Tech Solvr
  • 505
  • 1
  • 7
  • 25
  • That's not an IIFE. It's an anonymous function. – Barmar Jan 01 '16 at 17:48
  • @Barmar I checked the link you marked as Duplicate, and they are using jQuery in answers..I don't know how it is a duplicate of jQuery question ? – Tech Solvr Jan 01 '16 at 17:50
  • Also can you please share the link from the answer which is near to it – Tech Solvr Jan 01 '16 at 17:52
  • Only one of the answers uses jQuery. It also has a link to another question http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example with 25 more answers. – Barmar Jan 01 '16 at 17:53
  • @TechSolvr You are getting an error because you are building an array of numbers not an array of functions. Just console log `numbers` and you will see the issue. – Mihai Vilcu Jan 01 '16 at 17:54
  • Your attempt at the end was almost right. Get rid of `()` after `}` on the 4th line. – Barmar Jan 01 '16 at 17:54
  • @Barmar aaah Thx a lot Sir..and for the second link..which is more promising :) thx again !!!!! – Tech Solvr Jan 01 '16 at 17:57

0 Answers0