Let's take the following code for example:
const constVar = 'some string';
let letVar = 'some string';
var varVar = 'some string';
(function() {
console.log(window.constVar); // prints undefined
console.log(window.letVar); // prints undefined
console.log(window.varVar); // prints 'some string'
})();
According to the description of the const
statement by mdn:
This declaration creates a constant whose scope can be either global or local to the block in which it is declared.
And I assume let
works in the same way.
In this case, the "block" is contained within the global scope. I guess the important distinction here is that while const constVar
is "globally" accessible it still doesn't define it on the window
object.
Which leads me to think that global scope and the window
object are disparate. Which ultimately leads to 2 questions.
Why do variables declared using the
var
keyword get defined onwindow
and variables declared withconst
andlet
not defined onwindow
?What is the difference between "global scope" and the
window
object provided to us by browsers.