Jack Spar
Jack Spar

Reputation: 573

Javascript - scope chain

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.

Upvotes: 0

Views: 170

Answers (2)

Let me write your code in a different manner, to account for the scope.

var scope = {};
scope.foo = function() {
  var b = 2;   
  scope.bar()   
} 

scope.bar = function() {
// this will look for a property 'b' defined in the bar method, but it doesn's exist
  console.log(b); 
// changing the console.log call to match the changes made above, means it will 
// look like this
  console.log(scope.b)
// but now scope.b is also not defined
}

scope.foo();

In other words, when you try to access 'b' inside 'bar', it will search for it in the scope where 'bar' was created, not in the scope where 'bar' is called.

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72857

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:

enter image description here

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.

Upvotes: 3

Related Questions