Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 477
Gopika Sreekumar Avatar asked Dec 31 '25 21:12

Gopika Sreekumar


1 Answers

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
like image 67
Zahid Hasan Avatar answered Jan 02 '26 11:01

Zahid Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!