Example # 1 A
Example # 1 B
Take a look at Example # 1 B. Notice how, in the second console.log() statement, the output is 100. This is because that second console.log() statement is in the global scope, and in that scope the “i” variable is equal to 100. So, there we have it: two different scopes without even having used a function.
Example # 2 A
Example # 2 B
Now, in Example # 2 A, there are two “j” variables.
The first “j” variable is a global, equal to 100, and the second is defined inside of the for loop. And because it’s defined inside of a block, it has block-level scope. Now look at example # 2 B. Because “i” is global, the “i” variable increments, just as we would expect. But notice that the “j” variable is always 50 in each console.log() statement, even though there is a global “j” variable. This is because on each iteration of the for loop, a block-level “j” variable is declared using the let keyword, and it is incremented (just to demonstrate that with let, we can re-assign a variable value). So in this case, with each iteration of the for loop we have a block-scoped “j” variable and it is always 51. Note that the global “j” variable is ignored on line # 12.
Example # 3 A
Example # 3 B
In Examples # 3 A and # 3 B you’ll see a similarity to Examples # 1 A and # 1 B, the only difference being the use of the use of the const keyword instead of let when declaring our block-level version of the “i” variable.
Example # 4 A
Example # 4 B
Example # 5 A
Example # 5 B
Now Example # 5 A is virtually identical to Example # 4 A, except that we have not tried to increment the “j” variable. And when you look at Example # 5 B, you’ll see that we no longer have an error. In the console, the value of “j” is 50 every time.
A lot to take in here, but I think it’s worth keeping on your radar, given this very functional block-level scope now increasingly available in browsers.