I am having some confusion regarding this Closure thing. I have two separate codes below that look similar but their output are different.
function setup(x) {
var array = [];
for(var i=0;i<arguments.length;i++){
array[i]= arguments[i];
}
return array;
}
console.log(setup('a','b')); // will output ["a","b"]
--------------
function f() {
var i, array = [];
for(i = 0; i < 3; i++) {
array[i] = function(){
return i;
}
}
return array;
}
var a = f();
console.log(a()); //output: [function(),function(),function()]
console.log(a[0]()); //output: 3 //same output in a[1]() and a[2]() calls as well
Now my question is, how come the output is different? both of the codes above return an array. in the first code, it prints all elements in array correctly whereas in the second code, why doesn’t it print [1,2,3]???
In JavaScript, you have function statements and function expressions. The first declare named functions, the latter evaluate to a named or anonymous function. You’re using a function expression.
What I think you want to do is a call expression. All you have to do is to immediately call your function that returns
i.Also note that, in your problematic example, all closures return
3because all of them capture the same variablei.EDIT: To make the previous paragraph more clear, if you really wanted to have 3 distinct closures, you’d have to create a new scope for each one. Unlike other languages, Javascript doesn’t create scope just by opening a block. It only creates scope in functions. Here are two ways of doing this:
The next example, however, is wrong, because even though
nis declared in theforblock, it will be as if it has been declared at the top of the function and only initialized in theforblock. Remember, this is JavaScript, not Java, not C, not C#, not <whatever bracketed language>:Equivalent code: