Skip to content

Instantly share code, notes, and snippets.

@davidnormo
Created July 28, 2014 15:26
Show Gist options
  • Save davidnormo/c8cd3e4c4fce3186e46e to your computer and use it in GitHub Desktop.
Save davidnormo/c8cd3e4c4fce3186e46e to your computer and use it in GitHub Desktop.
Javascript Closures
/**
* Be careful of closure behaviour, it might not give you values you expect!
* For example when you have timeouts or event listeners.
*/
(function(){
var i = 0,
arr = ['a','b','c','d'],
doSomething = function(localKey){
console.log('i:', i);
console.log('localKey:', localKey);
};
arr.forEach(function(value, key){
i = key;
setTimeout(function(){
console.log('key:', key);
doSomething(key);
}, 1000);
});
})();
/* Output
key: 0
i: 3
localKey: 0
key: 1
i: 3
localKey: 1
key: 2
i: 3
localKey: 2
key: 3
i: 3
localKey: 3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment