5

Can anyone explain why document.write part always outputs 10?

 function creatFunctions() {
     var result = new Array();
     for (var i = 0; i < 10; i++) {
         result[i] = function () {
             return i;
         }
     }
     return result;
 }
 var funcs = creatFunctions();

 for (var i = 0; i < funcs.length; i++) {
     document.write(funcs[i]() + "<br />");
 }

I think the answer to this question is more thorough than the duplicate question, therefore worth keeping this post.

Blake
  • 7,367
  • 19
  • 54
  • 80
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Felix Kling Apr 21 '14 at 13:58

5 Answers5

9

Sure.

In your for loop, you reference i. What you expect to be happening is that each closure gets a snapshot of i at the time the function is created, therefore in the first function it would return 0, then 1, etc.

What's really happening is that each closure is getting a reference to the external variable i, which keeps updating as you update i in the for loop.

So, the first time through the loop, you get a function that returns i, which at this point is 0. The next time you get two functions which return i, which is now 1, etc.

At the end of the loop, i==10, and each function returns i, so they all return 10.

UPDATE TO ADDRESS QUESTION IN COMMENT:

It's a little confusing since you use i in two different contexts. I'll make a very slight change to your code to help illustrate what's going on:

function creatFunctions() {
    var result = new Array();
    for (var i = 0; i < 10; i++) {
        result[i] = function () {
            return i;
        }
    }
    return result;
}
var funcs = creatFunctions();

// NOTE: I changed this `i` to `unrelated_variable`
for (var unrelated_variable = 0; unrelated_variable < funcs.length; unrelated_variable++) {
    document.write(funcs[unrelated_variable]() + "<br />");
}

... the functions that you create in your creatFunctions() function all return i. Specifically, they return the i that you create in the for loop.

The other variable, which I've renamed to unrelated_variable, has no impact on the value returned from your closure.

result[i] = function () {
    return i;
}

... is not the same thing as result[2] = 2. It means result[2] = the_current_value_of_i

Jason
  • 13,606
  • 2
  • 29
  • 40
  • thanks for your reply! But I don't quite understand what you mean by `the next time you get two functions which return i`, shouldn't it be so that when i = 2, only `result[i] = function () { return i; }` will be executed, which means result[2] = 2? – Blake Apr 21 '14 at 14:00
  • 1
    @Blake: If `i` is `2`, you have `result[2] = function () { return i; }`, i.e. `result[0]`, `result[1]` and ``result[2]` all contain a function that returns `i`. – Felix Kling Apr 21 '14 at 14:04
  • I tried to address your question with an addition to my answer – Jason Apr 21 '14 at 14:09
4

Because you reference i as a variable, which, when the function executes, has the value 10. Instead, you could create a copy of i by wrapping in in a function:

(function (i) {
    result[i] = function () {
        return i;
    }
}(i));
jgillich
  • 71,459
  • 6
  • 57
  • 85
3

The i that you are returning inside the inner function - is the i that was declared inside the for(var i=0...) therefor - it is the same i for all of the functions in result and by the time you are calling the functions its value is 10 (after the loop ends)

to accomplish what you wanted you should declare another variable inside the scope of the anonymous function

Yaron U.
  • 7,681
  • 3
  • 31
  • 45
1

Because reference to "i" is boxed (enclosed) in your closure that you defined.

result[i] = function () {
             return i;
 }

And it just keeps reference to the "i" var which keeps changing with each iteration.

milagvoniduak
  • 3,214
  • 1
  • 18
  • 18
0

UPDATE

This is related to the this keyword function scope which defines variable context. Hence, in JavaScript, there's no such thing as block scope (for, if else, while, ...).

With that in mind, if you assign var funcs to a function definitioncall, the function body (this) will be bound to the global scope var i inside that function will reach the end of the for loop and stays there in memory. In this case i is 10.

Unfortunately for you, since function scope puts every variable to the top, var i will be global as well.

Although I was completely wrong at first, I stand corrected and took the liberty to create the output of your script in this demo.

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39
  • 1
    The closure "problem" has nothing to do with `this` and `i` inside `creatFunctions` is not global either. I also have no idea what you want to express with *"if you assign a variable to a function definition, the function body (this) will be bound to the global scope or function body"*. The function body isn't bound to anything (whatever that means) and the value of `this` is determined by *how* the function is *called*. – Felix Kling Apr 21 '14 at 14:00
  • You're right as I now see in [my fiddle](http://jsfiddle.net/tive/K8E5m/) my answer doesn't make sense and I didn't notice the call `func[i]()`. I'm gonna fiddle around a bit more and perhaps delete my answer if I can't figure it out. Apparently it's also still confusing to me and right now I need to get through this myself to improve. Thanks for the response ^^ – Tim Vermaelen Apr 21 '14 at 14:57