In light of questions:
Understanding let vs. var hoisting and
Are variables declared with let or const not hoisted in ES6?
I do not understand what happens when hoisting lifts a variable out of block scope, into global scope.
In my code, I have:
<script>
"use strict";
let PageInit = null;
document.addEventListener("DOMContentLoaded", () => {
PageInit = new IPageInit();
doSomething();
});
function doSomething() {
alert(PageInit.RefreshCounter); // 60 //correct
}
</script>
PageInit
being created in the global scope is visible to doSomething()
.
However, if I do this:
<script>
"use strict";
document.addEventListener("DOMContentLoaded", () => {
var PageInit = new IPageInit();
doSomething();
});
function doSomething() {
alert(PageInit.RefreshCounter); // referenceError
}
</script>
I am not understanding hoisting properly. I expected that var PageInit
inside block scope would get hoisted into global scope, first thing inside the <script>
tag.
But it doesn't.
Can anyone explain why not? Or where does it get hoisted to?
This never happens.
Hosting affects when a variable comes into existence, not where.
That implicitly declares a global. It isn't hosted. The variable doesn't exist until the function is run. Trying to read the variable before then will result in an exception.
var
declares a variable in the scope of the function it is declared inside. So it won't create a global.It is hoisted … but as it is the first line in the function, that makes no practical difference.