0

I came across this example in a Toptal youtube video that uses syntax that won't run in Chrome, unless I am missing something. This example comes up here (JavaScript closure inside loops – simple practical example) and the same syntax is used. Why is this not running for me/does the indicated line below contain valid syntax?

var x, y, funcs = [];

for(x=0; x<5; x++){

    (function(){
        var r = x;
        funcs.push(function(){
        console.log(r);
        });

    });
};  
for (var y=0; y<5; y++){
    funcs[y]();  //<< is this valid JS syntax/why is it not working for me?
};
Community
  • 1
  • 1
swoopedj
  • 115
  • 2
  • 12
  • 1
    What exactly is not working? – connexo Aug 16 '15 at 14:27
  • You declare y as [] and then again as index, this might not be working as expected. Also retrieve a return value when iterating your array and try to check the result in a debugger. – bash.d Aug 16 '15 at 14:28
  • 2
    The problem is not with the function call syntax; that's fine. The problem is that your first `for` loop isn't putting anything in the array. You've got an anonymous function that's *never called*, so the first loop does nothing. – Pointy Aug 16 '15 at 14:31

1 Answers1

3

You need to make this anonymous function inside your first for-loop self-executing by adding a pair of brackets () after the definition.

(function(){
    var r = x;
    funcs.push(function(){
    console.log(r);
    });

})();

Without this, you keep declaring a function inside your first loop which is never executed and thus, never pushes anything into your array.

After your first loop, do a console.log(funcs.length) and you will get a 0 since your array has no elements.

Your current code will give you uncaught type error: funcs[0] is not a function which is because funcs[0] is undefined.

connexo
  • 53,704
  • 14
  • 91
  • 128