At first basic for loop
for(let i = 0; i < 5; i++) {
const num = i * 2
console.log(num)
}
// 0 2 4 6 8
const can't reassign neither redeclare, but there is no any error.
So block scope might change each time
▼ then add setTimeout in this loop
for(let i = 0; i < 5; i++) {
const num = i * 2
setTimeout(function() {
console.log(num)
}, 1000)
}
// (after 1s)
// 0, 2, 4, 6, 8
If I use var ?
for(let i = 0; i < 5; i++) {
var num = i * 2 // ⭐ var !!!!
setTimeout(function() {
console.log(num)
}, 1000)
}
// (after 1s)
// ⭐⭐ 8 8 8 8 8
Why result is "8 8 8 8 8" ??
Because declare var in block scope is the same as declare var as global scope. var doesn't have block scope
//⭐ declare var in block scope is the same as like this
var num;
for(let i = 0; i < 5; i++) {
num = i * 2
setTimeout(function() {
console.log(num)
}, 1000)
}
// (after 1s)
// 8 8 8 8 8
- var
num changes(overwrite) 8 after 1ms when setTimeout() executes
- const
num declares each time loop, so even though the name num is the same, save in different memory places
ref. from this course
(note for myself)
var: setTimeout()が実行される1秒後には、numはもう8になっとる。var numはglobalなので、上書きされマッセ
const: loopごとに宣言されてます。numって名前一緒じゃけど、違うメモリスペースにありマッスル



Top comments (1)
Nice one.
I can't resist adding an example with both global and function-scoped var declarations to really illustrate the difference side-by-side.
The example above shows that
varscope can go down (eg from global into function) but not back up (from function out to global).Note for beginners following along
Accessing a global variable from within a function, the way
doubleCatsis doing here by accessingcats, is generally a bad idea. If your function requires external data, the preferred method would be to pass the data as an argument.My code above accesses the global var directly just to demonstrate how a globally scoped
varcan be accessed from a function block. Whether it should be accessed in this way is another question entirely.A more robust version of this function would look like this:
And, since we're being pedantic...
The
moreCatsvar is also unnecessary. Again, it's just an opportunity to show that the function-scoped variable cannot be accessed from outside of the function. In the real world, we'd just return the result directly without storing it in a variable: