Monday 18 June 2018

javascript - why don't const and let statements get defined on the window object




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.




  1. Why do variables declared using the var keyword get defined on window and variables declared with const and let not defined on window?



  2. What is the difference between "global scope" and the window object provided to us by browsers.



Answer




1. Why do variables declared using the var keyword get defined on window and variables declared with const and let not defined on window?




Because the specification says so. If you are asking for the reason behind that decision, then you should reach out to the specification maintainers.



Classes do not become properties of the global object either btw.





2. What is the difference between "global scope" and the window object provided to us by browsers.




There are two types of base environment records according to the spec:




  • Declarative Environment Record

  • Object Environment Record




A Declarative Environment Record is basically your standard environment that you get when calling a function. All bindings (variables, constants, etc) are defined in some internal data structure that cannot be accessed from normal code.



An Object Environment Record on the other hand uses an actual JavaScript object to store bindings. This is used for example by the now deprecated with statement:





with({foo: 42}) {
console.log(foo);

}





Now, a Global Environment Record actually consists of two environment records: A declarative environment record and an object environment record. The object environment is backed by the global object, i.e. window and contains var declarations and other globals that the browser provides. The declarative environment contains the let, const, class, etc declarations.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...