Created
April 4, 2012 05:33
-
-
Save ithayer/2298045 to your computer and use it in GitHub Desktop.
Simple example of Javascript variable hoisting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Simple demonstration of function scope. | |
| var n = 1; | |
| function printSomething() { | |
| console.log(n); | |
| var n = 2; | |
| console.log(n); | |
| } | |
| => printSomething(); | |
| undefined | |
| 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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