0

When we declare a variable with the var keyword in the global scope var x = 10;, a property with the same name is created in the global object (window, global, self, globalThis, depending on the environment). So, here is my question:

If I try to access that variable console.log(x) js will look for it into my declared code first to see if its there or it will jump directly to the global object? I know that if I do this:

let myVar = 20;
globalThis.myVar = 30;

console.log(myVar) // 20, so my let declaration is readed first.

But what happens with var declarations?

Diego Perdomo
  • 443
  • 2
  • 4
  • 14
  • Does this answer your question? [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Victor Alessander Apr 26 '20 at 19:30
  • In the global scope, the `let` keyword does not create a property on the global object (globalThis), while `var` keyword does. – mateleco Apr 26 '20 at 19:32
  • I know this, now, change the let declaration for a var. Which one is readed first? ```var myVar``` or ```globalThis.myVar```? – Diego Perdomo Apr 26 '20 at 19:42
  • @DiegoPerdomo There's not really a difference. In the global scope, they are the *same*. Normal scoping rules for identifiers apply, and if there is no local (or lexical) variable of that name, it reads from the scope that is backed by the global object. – Bergi Apr 26 '20 at 19:44

1 Answers1

1

In browser children of window object are directly accessible by their names without explicit window. when you create a local variable however you shadow the name even if exists under window so yes local will be accessed first

In programming this is called variable shadowing you can read more on the wiki I linked

PS. If you are on global scope and use var it will be as if you declared the thing under window itself I will demonstrate this with a snippet

var foo = 12;
console.log(window.foo)//12
window.foo=10
console.log(foo)//10

//However if you use let or const this will not happen
nikoss
  • 3,254
  • 2
  • 26
  • 40
  • So if I have ```var myVar``` and ```globalThis.myVar``` the ```var myVar``` is readed first? – Diego Perdomo Apr 26 '20 at 19:43
  • javascript get all sorts of confusing when it comes to scoping with var due to something called hoisting that is the reason why const and let was made however if you mean `window` by `globalThis` yes your local variables are always prefered and if you want to use the global version you should explicitly use `window` keyword however if you are on global scode by yourself your var defition will be the same thing as window version let me update my answer – nikoss Apr 26 '20 at 19:47
  • @nikoss Hoisting has nothing to do with this. And `let`/`const` are in fact still hoisted. – Bergi Apr 26 '20 at 19:54