javascriptjavascript-objectsjavascript-scope

Why does accessing 'window.variable' return 'undefined' when using 'let' but not with 'var'?


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).


Solution

  • There are two points in here:

    1. variables declared with var in the global scope are added as a properties to the global object and making them accessible as properties of that object.
    2. variables declared with let and const 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 object