Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Last active February 22, 2017 16:55
Show Gist options
  • Save ivan-ha/3100ca7b1241f6c164a40f609fef5251 to your computer and use it in GitHub Desktop.
Save ivan-ha/3100ca7b1241f6c164a40f609fef5251 to your computer and use it in GitHub Desktop.
js closure explanation
// same execution context, all pointing to same memory location
// so by the time running console.log(i), i will be its final value (i.e. 3)
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
function () {
console.log(i);
}
);
}
return arr;
}
// create diff. execution context by invoking IIFE
// so each j will store the immediate value of 1 (i.e. 0, 1, 2), pointing to diff. memory location
function buildFunctions2() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
(function (j) {
return function () {
console.log(j);
}
}(i))
);
}
return arr;
}
var fs = buildFunctions();
var fs2 = buildFunctions2();
console.log(fs[0]()); // print 3
console.log(fs[1]()); // print 3
console.log(fs[2]()); // print 3
console.log(fs2[0]()); // print 0
console.log(fs2[1]()); // print 1
console.log(fs2[2]()); // print 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment