0

Im new in javascript and in programming.

If I declare a variable with var I see that my variable is declared globally and my variable is inside the window object. Example:

var element1 = 1;
window.element1; //This returns 1

But when I use let I can't access my variable using the window object. Example:

let element2 = 1;
window.element2; //This returns undefined

So, where has been my variable element2 been declared? What is the scope of element2 ?

  • 1
    [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) does not create properties of the window object when declared globally (in the top-most scope). – Rayon Aug 15 '20 at 16:54

1 Answers1

1

You are confusing scope and automatic attachment to the default object.

If you use let or var outside of any block, function, or module then the scope will be global.

var will also attach a property of the same name to the default object (which is window in the case of JS running in a browser).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335