callback - 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 remove line console.log(x) , replace console.log('hello!') , put breakpoint on line in webstorm, , if try evaluate x, says "referenceerror: x not defined".

why that? how webstorm works or javascript have sort of pre-processor includes variables being used in function, in it's closure?

the javascript compiler examines function, , determines free variables references, , variables put closure environment. if don't have console.log(x) in function, doesn't need put x environment.

for related question, see

definition of 'closures'


Comments