1
    var arr = [];
    for(var i=0; i<5; i++){
        arr[i] = function(){
            return i;
        };
    }
    document.write(arr[1]());

the output is 5, as I expected

but when i added i++ between return i; and the end of the for loop, like the code below,

    var arr = [];
    for(var i=0; i<5; i++){
        arr[i] = function(){
            return i;
        };
        i++;
    }
    document.write(arr[1]());

screen shows the error, Uncaught TypeError: arr[1] is not a function

i expected that output should be 6, but i cannot understand why.

3
  • Becuase after your first loop i will be 2. I suggest using some debugging tools to look at your variables or add some console.log()'s to your code to understand what's going on next time. Commented Jun 29, 2017 at 12:36
  • Because you're increasing the index by 2, array[0], array[2], array[4]... Commented Jun 29, 2017 at 12:36
  • Are you also expecting all the functions within arr to output the same value? That's what will happen. Commented Jun 29, 2017 at 13:21

1 Answer 1

6

Because you've got two increments for i, the assigned elements of the array will be 0, 2, and 4. Element 1 is skipped.

The first assignment happens when i is 0. Then, i is incremented to 1 at the end of the loop, and then again to 2 in the third clause of the for loop header. So the next assignment is for element 2.

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

4 Comments

I can accept your answer 11mins later, anyway, thank you
Also, without a closure won't all the functions within arr will output 5.
@evolutionxbox yes that's true but apparently the OP already knows that; it's mentioned in the question.
Good point! I missed the last line, except the output won't be 6 it'd be 5.

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.