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:
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.
b
is defined in foo
's scope.
bar
is called from foo
's scope, yes, but it's defined outside of foo
's scope. This means that bar
can not access b
.
As an image can often help:
Consider each red square to be a "scope". foo
and bar
share the outer scope, but they can't access each other's inner scope.