0
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?

Ayush
  • 709
  • 2
  • 8
  • 17
  • 1
    Webstorm's debugger is probably operating in [Strict Mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) – Rob M. Sep 01 '16 at 21:45
  • @RobM. I have "use strict" at the top of my script as well. How does strict mode affect this? – Ayush Sep 01 '16 at 21:56

1 Answers1

3

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'

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612