0

According to the Node documentation, the top-level scope is not the global-scope, and a variable defined insiede a Node.js module will be local to that module.
However, I noticed that var something created in the global scope gets listed as a property of global, which to me seems to be a sort of cross-module object. Here is the code I ran in GitBash:

$ node
var something = "this is a test"
undefined
something
'this is a test'
console.log(global)

I really don't get how this reconciles with what is stated in the documentation about the top-level scope.

If global really is a cross-module object, as Ebohlman's answer to this old question seems to suggest, then var something is not local to the module it gets defined in.

Could someone help me shed some light on this matter? Is var something really module-scoped? How is global different from window in JavaScript? What's its purpose?

  • 1
    The top-level scope of a *module* is not the global scope, yes. Where did you put and run your `var something`? – Bergi Sep 08 '18 at 19:15
  • @Bergi thanks for getting back to me. I ran it with GitBash. –  Sep 08 '18 at 19:16
  • You mean you ran `node` to start the node REPL and then entered `var something`? – Bergi Sep 08 '18 at 19:18
  • @Bergi precisely. I edited my question adding the snippet of code that I ran. –  Sep 08 '18 at 19:26
  • Have a look at [this](https://stackoverflow.com/q/25122257/1048572). The docs you read are inaccurate, they should state that "*the top-level scope **of a module (script file)** is not the global scope*". See also https://nodejs.org/api/repl.html and https://nodejs.org/api/modules.html – Bergi Sep 08 '18 at 19:35

1 Answers1

0

You ran the code in a REPL, meaning that all the code you typed in after running node is in the same scope, which is not the same as declaring and running several modules, so you didn't reproduce an error which we can help with here.

johnheroy
  • 416
  • 2
  • 7
  • sorry for asking a possibly daft question. May I just know why running the same few lines from the terminal in Visual Studio returns a different result? In this case `var something` doesn't get listed as a property of `global`. –  Sep 08 '18 at 19:51
  • Not sure - your question was about modules and you're trying to reproduce an error by running Node.js from the command line which are two different things. If ultimately you want to test leaking global scope between two Node.js modules, why not write two really simple modules and test that way? – johnheroy Sep 08 '18 at 19:57