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?

4
  • Does this answer your question? What's the difference between using "let" and "var"? Commented Apr 26, 2020 at 19:30
  • In the global scope, the let keyword does not create a property on the global object (globalThis), while var keyword does. Commented Apr 26, 2020 at 19:32
  • I know this, now, change the let declaration for a var. Which one is readed first? var myVar or globalThis.myVar? Commented Apr 26, 2020 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. Commented Apr 26, 2020 at 19:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

So if I have var myVar and globalThis.myVar the var myVar is readed first?
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 Hoisting has nothing to do with this. And let/const are in fact still hoisted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.