Skip to content

Instantly share code, notes, and snippets.

@jsec516
Last active December 7, 2015 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsec516/40cd2e39b69a2f71de83 to your computer and use it in GitHub Desktop.
Save jsec516/40cd2e39b69a2f71de83 to your computer and use it in GitHub Desktop.
Closure behavior experimented
function foo(){
var a = 2;
function bar(){
console.log( a );
}
bar(); // 2 not-closure, regular lexical scope actually
}
foo();
/*======= closure ==============*/
function foo(){
var a = 2;
function bar(){
console.log(a);
}
return bar;
}
var baz = foo();
baz(); // 2 -- closure observed here
/*============== weird piece of code ====================*/
for (var i=1; i<=5; i++){
(function(){
setTimeout(function time(){
console.log(i);
}, i*1000);
})();
}
// result is 6 - for 5 times but we expected 1,2,3,4,5
for (var i=1; i<=5; i++){
(function(i){
setTimeout(function time(){
console.log(i);
}, i*1000);
})(i);
}
// result is 1,2,3,4,5 because we created scope variable j to remember value of i in the scope of closure
for (var i=1; i<=5; i++){
let j = i;
setTimeout(function time(){
console.log(j);
}, j*1000);
}
// works as above because let defines for each loop scope.
for (let i=1; i<=5; i++){
setTimeout(function time(){
console.log(i);
}, i*1000);
}
// works as above because let defines for each loop scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment