Variable declaration and hoisting

Photo by Joshua Aragon on Unsplash
var x = function() {
return a;
var a = 1;
function a() { return 'hello'}
}
LexicalEnvironment:
outer: VariableEnvironment
VariableEnvironment:
a = function () { return 'hello' }
outer: global
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i + i + '' + i)
}, i*10)
}
00
21
42
63
84
105
105
105
105
105
LexicalEnvironment:
outer:
LexicalEnvironment:
outer: VariableEnvironment
LexicalEnvironment:
outer: VariableEnvironment
LexicalEnvironment:
outer: VariableEnvironment
LexicalEnvironment:
outer: VariableEnvironment
LexicalEnvironment:
outer: VariableEnvironment
VariableEnvironment:
i = 5
outer: global

A closure is a record storing a function together with an environment.

for (var i = 0; i < 5; i++) {
let closure = (j) => () => console.log(j + j + '' + j)
setTimeout(closure(i), i*10)
}
LexicalEnvironment:
outer:
LexicalEnvironment:
j = 0
outer: VariableEnvironment
LexicalEnvironment:
j = 1
outer: VariableEnvironment
LexicalEnvironment:
j = 2
outer: VariableEnvironment
LexicalEnvironment:
j = 3
outer: VariableEnvironment
LexicalEnvironment:
j = 5
outer: VariableEnvironment
VariableEnvironment:
i = 5
outer: global
for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i + i + '' + i)
}, i*10)
}
LexicalEnvironment:
outer:
LexicalEnvironment:
i = 0
outer: global
LexicalEnvironment:
i = 1
outer: global
LexicalEnvironment:
i = 2
outer: global
LexicalEnvironment:
i = 3
outer: global
LexicalEnvironment:
i = 4
outer: global