2

I have a question regarding the outer environment in JS. Suppose I have the code like this:

function callbackTest(callback) {
  var a = 1;
  callback();
}
callbackTest(function() {
  console.log(a);
});

The brower told me that a is not defined. It means the outer environment is the global context, but I created the function within callbackTest, so I assume the outer environment of callback is the callbackTest. Can somebody tell me why? Thx!

Chris Yao
  • 21
  • 2
  • It doesn’t matter which function calls which, it only matters where the functions are declared. A variable (scoped to a function) can only be accessed by the function the variable is declared in or any inner function nested in that function (declared inside it). – Sebastian Simon Jan 11 '17 at 18:21
  • Scope is determined by where the function is defined, not where it's called. – Madara's Ghost Jan 11 '17 at 18:30

3 Answers3

3

but I created the function within callbackTest

No you didn't. The function is created here outside of callbackTest:

callbackTest(function() {
  console.log(a);
});

Maybe it's easier to see if you split this into two statements:

var f = function() {
  console.log(a);
};
callbackTest(f);

The function is created in global scope. It is only called inside callbackTest. But since JavaScript has lexical scope and not dynamic scope, it cannot access a.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

The variable a is defined inside the scope of the function callbackTest. It doesn't matter where you call the function. The scope is still restricted to that function. Even the following would be undefined:

function callbackTest() {
  var a = 1;
}
callbackTest();
console.log(a);

You must define the variable a in outer scope, where all codes share:

var a;

function callbackTest(callback) {
  a = 1;
  callback();
}
callbackTest(function() {
  console.log(a);  // Now outputs 1
});
Kousha
  • 32,871
  • 51
  • 172
  • 296
0

The scope (environment) of a function is not defined where you call it, it is defined where you created it. Your callback function is defined when you called the callbackTest function and not inside its body. That is why the callback is not aware of the variable that is inside, its scope is whatever scope is active when called the callbackTest function.

M0nst3R
  • 5,186
  • 1
  • 23
  • 36