Last active
July 29, 2018 15:36
-
-
Save andrelandgraf/b77bd34339dfd3c6036825fc6d244f18 to your computer and use it in GitHub Desktop.
working with var vs let in for loops
This file contains 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
// the scope of a let variable is the current block scope | |
// the scope of a var variable is the current function scope (if there is no function, than the scope is global) | |
// using var in this example will execute the loop and compute var i to the value 10 | |
// than the timeout callbacks will callback one after the other and access i which is globally set to 10 | |
for(var i = 0; i < 10; i++){ | |
setTimeout(function () { | |
console.log(i); | |
}, 1500, i); | |
} | |
/* | |
* Output: | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
* 10 | |
*/ | |
// using let instead means that within every loop scope (block), you are working with another shadowed variable i | |
for(let i = 0; i < 10; i++){ | |
setTimeout(function () { | |
console.log(i); | |
}, 1500, i); | |
} | |
/* | |
* Output: | |
* 0 | |
* 1 | |
* 2 | |
* 3 | |
* 4 | |
* 5 | |
* 6 | |
* 7 | |
* 8 | |
* 9 | |
*/ | |
// even better: use the functional programming paradigm to pass i by value to the inner function of setTimeout(), | |
// works as expected for both let and var | |
for(var i = 0; i < 10; i++){ | |
setTimeout(function(i){ | |
console.log(i) | |
}, 1500, i); | |
} | |
// or even shorter, using an anonymous arrow function: | |
for(var i = 0; i < 10; i++){ | |
setTimeout((i) => console.log(i), 1500, i); | |
} | |
/* | |
* Output: | |
* 0 | |
* 1 | |
* 2 | |
* 3 | |
* 4 | |
* 5 | |
* 6 | |
* 7 | |
* 8 | |
* 9 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment