Last active
September 27, 2017 12:06
-
-
Save joeytwiddle/faecbf56ed65f892dfbf23110c7d55a8 to your computer and use it in GitHub Desktop.
ES6 scoping with let and for
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
'use strict' | |
// For scoping is a bit surprising. | |
// Although i appears to be a persistent variable between iterations, | |
// actually there is a separately scoped i for each iteration! | |
for (let i = 0; i < 5; i++) { | |
setTimeout(() => console.log(i), 10 * i) | |
} | |
// Prints: 0, 1, 2, 3, 4 | |
// The same is not true for the while loop. There is only one j. | |
let j = 0; | |
while (j < 5) { | |
setTimeout(() => console.log(j), 100 + 10 * j) | |
j++ | |
} | |
// Prints: 5, 5, 5, 5, 5 | |
// In fact it appears the for loop introduces a "middle" scope | |
// Look at the three scopes here: | |
let x = 5 | |
for (let x = 0; x < 10; x++) { | |
let x = 3; | |
console.log(x); | |
} | |
// Pretty crazy right? | |
// By the way, this local scope means you can use const in these loop constructs: | |
for (const key in object) { | |
console.log(key); | |
} | |
for (const item of array) { | |
console.log(item); | |
} | |
// Although not in the classic C-style for we used earlier |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment