Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.