Skip to content

Instantly share code, notes, and snippets.

@rashkov
Created February 7, 2017 16:41
Show Gist options
  • Save rashkov/c1d70e4db8853c72b5c756c840d83194 to your computer and use it in GitHub Desktop.
Save rashkov/c1d70e4db8853c72b5c756c840d83194 to your computer and use it in GitHub Desktop.
printing/console.log from a for loop, block scoping, and ES5 vs ES6
// A simple async function that resolves immediately
let asyncFn = ()=> {
let handlers = (resolve, reject)=> {
resolve();
}
return (new Promise(handlers));
}
// Lack of default block scoping can be confusing. Especially with for loops
// Say, someone might start with this:
for (var i = 0; i < 10; ++i) {
asyncFn().then(function() { console.log(i); });
} // Prints all 10s
// Then when they realize why this doesn't work, try something like:
for (var i = 0; i < 10; ++i) {
var j = i; // this is inside the block, so it's scoped to it, right?
asyncFn().then(function() { console.log(j); });
} // Prints all 9s
// Turns out that for loops don't actually create block scoping, even though they use curly braces
// Have to create scope/closure using an immediately-invoked-function-expression
for (var i = 0; i < 10; ++i) {
(function(){
var j = i;
asyncFn().then(function() { console.log(j); });
})();
}
// Can achieve the same thing using the fancy new (ES6) block-scoped let declaration
for (var i = 0; i < 10; ++i) {
let j = i;
asyncFn().then(function() { console.log(j); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment