Search code examples
javascriptcallbackclosureswebstorm

When do variables become part of a JavaScript function's environment?


var x = "hi!";
request(url, function(error, response, body) {
    console.log(x);    //prints "hi!"        
});

If I remove the line console.log(x) and replace it with console.log('hello!') and put a breakpoint on that line in the WebStorm, and if I try to evaluate x, it says "ReferenceError: x is not defined".

Why is that? Is it just how WebStorm works or does JavaScript have some sort of a pre-processor that only includes variables being used in a function, in it's closure?


Solution

  • The Javascript compiler examines the function, and determines which free variables it references, and only those variables are put into the closure environment. If you don't have console.log(x) in the function, then it doesn't need to put x into the environment.

    For a related question, see

    Definition of 'closures'