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?
};
3
  • 1
    What exactly is not working? Commented Aug 16, 2015 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. Commented Aug 16, 2015 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. Commented Aug 16, 2015 at 14:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Probably should pass x to the function as well to avoid the closure/loop problem.
That shouldn't be required since all anonymous functions in the array have declared their own var r.
They do, that's true; I guess that should work fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.