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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.