javascript - Stop passing by reference in closures -
this question has answer here: how javascript closures work? 88 answers i have code looks this: var = []; for(var = 0; < 10; i++) { a[i] = function() { console.log(i); } } unfortunately, seems i being passed reference, functions in a output 10. how make each function outputs value i had when created? i.e. a[0]() gives 0, a[1]() gives 1, etc. edit : clarify, not want a store values 0-9. want a store functions return values 0-9. you need invoke function (to create closure captures value) returns function (the 1 want end with). this: var = []; (var = 0; < 10; i++) { a[i] = (function(value) { return function() { console.log(value); } })(i); }