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?