[1][ecmascript 5.1](http://www.ecma-international.org/ecma-262/5.1/)[2][interpreted language definition](https://en.wikipedia.org/wiki/Interpreted_language) [3] V8 engine wikipedia [4][rhino](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino)
var foo = "bar";
function bar() {
var foo = "baz";
function baz(foo) {
foo = "bam";
bam = "yay";
}
baz();
}
bar();
console.log(foo);
console.log(bam);
baz();
for this compilation phase let's stick to Kyle Simpson's explanation of this phase. This helped me understand a lot about some (common) mistakes and avoid them ... let's start with a "simple" example and apply it's simple rules.
In the Global scope
Hey global scope, I have a bar() function declaration.. it will be registered in the global scope now we enter the scope of bar:
Hey scope of bar, I have a baz() function declaration ... so the scope of bar will register it now we enter the scope of baz
This ends the compilation phase:
Scope declaration value
------ ----------- -----
global foo variable
global bar function
bar foo variable
bar baz function
baz foo variable
(note fro the reminder : LHS = Left Hand Side and RHS = Right Hand Side)
line 1 : Hey global scope, I have an LHS reference for variable called foo, do you have it ? => the global scope has it and give it to perform the assignment.
line 2 to 12 : nothing to execute for now
line 13 : Hey global scope, I have an RHS for variable called bar, do you have it ? => yes, and the global scope will return it to the caller. in fact this is a function and giving it the parenthesis, we will execute it.
line 4 : Hey scope of bar, I have an LHS reference for variable called foo, do you have it ? => yes and it is returned for assignment. var foo of local baz scope is shadowing the var foo of global scope
line 6-9: is a declaration
line 10 : Hey scope of bar, I have an RHS reference for variable called baz, do you have it ? => yes, here it is, and execution is done through parenthesis. fortunatly, baz is also a function that we can execute
line 7 : Hey scope of baz, I have an LHS reference for variable called foo, do you have it ? => yes and it is returned for assignment.
line 8 :
line 14 : Hey global scope, I have an RHS reference for variable called foo, do you have it ? => the global scope has it and give it back. => it's vlue is 'bar' (because here we are talking about the variable foo of the global scope, not the one of the bar or baz scope.
line 15 : Hey global scope, I have an RHS reference for variable called bam, do you have it ? => the global scope has it and give it back. => it's vlue is 'yay'
line 16 : Hey global scope, I have an RHS reference for variable called baz, do you have it ? => no => for RHS, it's not going to create one for me, like it would if it had been a LHS => reference error, because there is no Identifier baz (this is true for strict and non strict mode)