Reputation: 43
I know that a global variable is a variable with global scope. I know that global scope means it can be seen by all. Does that mean, in node.js
, that n
here is a global variable?
let n = 1
function f() {}
...
I've also read that a global variable can be defined as a property of the global object e.g. global.clearInterval
. global.clearInterval
can be seen anywhere so has global scope. Is it right to call a property of the global object a global variable?
Upvotes: 1
Views: 92
Reputation: 1074495
Does that mean, in node.js, that
n
here is a global variable?
It depends on how you run it. By default, no, because Node.js treats your code as a module, not a script. Top-level declarations in modules aren't globals, they're scoped to the module.
If you were running that code as a script, then n
(and f
) would be global variables (although, amusingly, they're different kinds of global variables; more below). With Node.js, you can run code at global scope by feeding the code directly into Node.js instead of giving it a file to execute. So if you have:
file.js
:
function f() { }
console.log(global.f === f);
And you do this:
node file.js
you'll see false
, because f
isn't a global. But if you do:
node -e "function f() { } console.log(global.f === f);"
you'll see true
, because code you pass in the -e
("eval") option is executed at global scope. (You can also do it from a file by redirecting the file into node
instead of having node
read the file directly: node < file.js
.)
Note that n
won't be a property of global
either way, though, because it's a different kind of global.
I've also read that a global variable can be defined as a property of the global object e.g.
global.clearInterval
.global.clearInterval
can be seen anywhere so has global scope. Is it right to call a property of the global object a global variable?
Yes, mostly. That is: properties of the global object are global variables, but JavaScript actually has two kinds of global variables: Ones that are properties of the global object, and ones that aren't. At global scope, var
and function
declarations create global variables that are properties of the global object, but let
, const
, and class
declarations create globals that aren't properties of the global object.
The global environment that uses the global object is the "outer" global environment. The one where identifiers created by using let
, const
, and class
declarations at global scope is the "inner" global environment. That means that let
/const
/class
globals shadow globals on the global object, just like local variables in a function shadow variables declared outside the function.
Side note: Beware that global
is a Node.js-specific global not present in most other JavaScript environments. ES2020 adds a new predefined global, globalThis
, which is the same value that this
has at global scope (which, traditionally, refers to the global object), which takes the place of Node.js's global
.
Upvotes: 2