I seek to understand this Javascript phenomenon
I'll paste code below displaying this phenomenon; it will contain 2 functions, buildFunctions1 and buildFunctions2. Both of them will return an array holding 3 functions that perform a rather simple function. ``` function buildFunctions1() { var arr = []; for(var i = 0; i < 3; i++) { arr.push(function() { console.log(i); }); } return arr; } var builtFunctions1 = buildFunctions1(); for(var i = 0; i < builtFunctions1.length; i++) { builtFunctions1[i](); } //prints 3 3 3 console.log('======================'); function buildFunctions2() { var arr = []; for(var i = 0; i < 3; i++) { arr.push((function(j) { //will save j return function() { console.log(j); }; }(i))); } return arr; } var builtFunctions2 = buildFunctions2(); for(var i = 0; i < builtFunctions2.length; i++) { builtFunctions2[i](); } //prints 0 1 2 ``` It is a bit counter-intuitive that buildFunctions1 will make all 3 functions print the same number, and I'm not quite sure why buildFunctions2 fixes this issue. I would love to understand javascript's logic on this so I can wittingly avoid bugs like this in the future.
In the interpreter, variables are usually pointers. In buildfunctions1() each element of the array is a pointer to the function in the code. buildfunctions2() produces separate functions with distinct values.
Join our real-time social learning platform and learn together with your friends!