Variable declared with var
and functions in script at global scope level, are a able to accessed with variable_name and window.*variable_name*
.
var foo = "10";
let bar= "20";
function func(){
}
console.log(foo); //10
console.log(window.foo); //10
I was in an understudying on:
var foo
, the identifier foo
binding is created and maintained by
Global Execution Context > Realm > Global Environment Record 's Object
Record.let bar
, the identifier bar
binding is created and maintained by
Global Execution Context > LexicalEnvironment > Global Environment Record's
Declarative Record .When JS tries to access a variable X
in global code. Does it first check for its binding at Global Environment Record 's Object Record followed by Global Environment Record's Declarative Record. How would JS know which record X
binding is available.
Does is first check for its binding at Global Environment Record 's Object Record followed by Global Environment Record's Declarative Record. How would JS know which record X binding is available
No, JS first checks the declarative environment for the identifier, and then checks the global object. This is outlined in the HasBinding() method of the Global Environment Record, where you can first see it check the declarative environment and then the global object. This method is used when resolving an identifier in the abstract operation GetIdentifierReference().
You can also see this in action in the below code, const name = ...
creates a binding on the declarative environment record of the Global ER, and then accessing it with console.log(name);
prints its value, not the value of window.name
(which would be printed if the global object was being checked first rather than the declarative environment).
const name = 123;
console.log(name);
console.log(window.name);