Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading