3

I understand there is no block level scope for var i ; however, in the following code, d.push(); is executed after the initialisation of i, why i here remains undefined?

var d = [];
for (var i = 0; i < 3; i++) {
     d.push(function(i) {
        console.log('iterator: ' + i);
    });
}
d[0]();//undefined

Any thoughts will be appreciated

1
  • You pushed anounymous function function(i) { console.log('iterator: ' + i); } which has a parameter i. But when you call the function, d[0]();, you didn't pass any argument. Commented Oct 11, 2015 at 1:57

2 Answers 2

2

You can push an argument-bound version of the anonymous function by using .bind() thereby ensuring the value of the first argument.

var d = [];
for (var i = 0; i < 3; i++) {
    d.push((function(i) {
        console.log('iterator: ' + i);
    }).bind(this, i));
}
d[0](); // iterator: 0
d[1](); // iterator: 1
d[2](); // iterator: 2
Sign up to request clarification or add additional context in comments.

Comments

2

Here's my solution:

var d = [];

function newFunction(i) {
    var k = i; 
    return function() {
        console.log('iterator: ' + k);
    }
}
for (var i = 0; i < 3; i++) {
     d.push(
        newFunction(i)
    );
}
d[0]();
d[1]();

This works because when you create the new function, it creates a variable scope that doesn't change with your for loop. It saves the state of i on each iteration so that when you call them again, it runs with the i it was originally declared with.

Comments

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.