I read a number of articles about the javascript scope chain and I thought I had a decent understanding of it. However, a very simple exercise made me realize I do not yet understand it at all.
I created the following code.
function foo () {
var b = 2;
bar()
}
function bar () {
console.log(b);
}
foo();
This code gives a reference error. However, I assumed that it would still print out 2. My reasoning was the following:
- Function declaration of foo and bar.
- Foo is executed, this creates a new execution context. Foo has internal property [[Scope] set to global.
- var b is hoisted.
- var b is assigned 2.
- bar is executed inside of the foo execution context. Therefore, I assumed the internal property [[Scope]] of the bar function would be set to foo.
- b is not defined in function bar, therefore the scopechain is looked up and finds the value b = 2.
- console.log(2);
My reasoning is based on that I understand that the [[Scope]] internal property of function X is set to the execution context that is running at the time function X is executed. Not based on where function X is declared.