While developer a client side application I ran into an error that I believe is related to my incomplete understanding of use of closures. I have trimmed down my code to the following :
var fn1 = function(arr){
return function(val){
var idx;
var x = 20;
for (idx in arr) {
arr[idx]();
}
}
}
var fn2 = fn1([function(){
x+= 20;
alert(x);
}])
Now upon executing :
fn2()
I receive an error :
ReferenceError: reference to undefined property "x"
I would like to know why this error is arising and why can't fn2 access the variables defined in the local scope of closure function returned by fn1 ?