Variable declaration and hoisting

Javascript Baseline pt. 1

Artem Dracontis
Feb 4, 2019 · 4 min read
Image for post
Image for post
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.

To make it even simpler, closure is javascript function that have access to its own variables and all other variables declared outside in parent function definition or even globally.

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store