Consider the following code snippets:
// Using var
var val = 20;
console.log(window.val); // Outputs: 20
// Using let
let val = 20;
console.log(window.val); // Outputs: undefined
In both cases, val
is declared in the global scope, yet accessing window.val
returns undefined
when using let
, while it correctly returns 20 when using var
.
How var
and let
differ in their interaction with the global object (window
in a browser environment).
3
Answers
There are two points in here:
var
in the global scope are added as a properties to the global object and making them accessible as properties of that object.let
andconst
in the global scope are not added as a properties to the global object. They exist in the scope but do not create properties on the global objectFrom- JavaScript: The Definitive Guide
In web browsers, the
Window object
serves as the global object for all JavaScript codecontained in the browser window it represents. This global Window object has a self referential window property that can be used to refer to the global object.
Yes, It is
undefined
Here it is why?When you declare a variable with
var
, it is hoisted to the top of its scope (including the global scope) and becomes a property of the global object. Hence, when you accesswindow.val
after declaringvar val = 20
, you can retrieve its value, which is 20.On the other hand, variables declared with
let
have block scope, meaning they are only accessible within the block in which they are defined. In this case, the block is the global scope. However, unlikevar
,let
variables are not added as properties to the global object. Therefore, when you try to accesswindow.val
after declaringlet val = 20
, it returns undefined becauseval
is not a property of the global object.