From my understanding, all properties created are given the value of undefined after the execution phase of the Execution Context - then, during the creation phase, the JS engine goes through the script, line by line, and assigns a value if it finds an = operator. With this in mind:
console.log(window);
var myVar = 1;
From the above snippet, why does the myVar property, within the global object, show a value of 1? I would have thought it would show a value of undefined, as this is what it was set to during the execution phase? If I try to access the property directly, like:
console.log(window.myVar);
var myVar = 1;
I DO see the value as undefined... it's only when I log the entire global object I'm seeing the value as 1. Am I missing something here?
Note - this is simply for learning purposes.
this has nothing to do with the window object, this is called hoisting
Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
another example would be
function test(){
console.log(myVar);
var myVar = 1;
}
test()
this would still log myVar as undefined. while omitting the myVar would throw an Exception..
Edit:
this only happens in the chrome console, it would be undefined otherwise.