Skip to content

Instantly share code, notes, and snippets.

@ithayer
Created April 4, 2012 05:33
Show Gist options
  • Select an option

  • Save ithayer/2298045 to your computer and use it in GitHub Desktop.

Select an option

Save ithayer/2298045 to your computer and use it in GitHub Desktop.
Simple example of Javascript variable hoisting
// Demonstration of how easy it is for this to mess up your loops.
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
var msg = txt[i];
setTimeout(function() { alert(msg); }, i*1000);
}​
// Alerts 'c', 'c', 'c'
// Simple demonstration of function scope.
var n = 1;
function printSomething() {
console.log(n);
var n = 2;
console.log(n);
}
=> printSomething();
undefined
2
// Pattern to avoid that by binding to variable in another function.
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout((function(msg) {
return function() { alert(msg); }
})(txt[i]), i*1000);
}​
// Alerts 'a','b','c'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment