here is some code
// app.js
let foo = 3;
let bar = 35;
in the browser i could do window.foo and i will get my 3
Not in a browser using a JavaScript engine that correctly implements let
you won't. let
creates a global variable, but not a property on the global object. This is a new concept in ES2015. (So do const
and class
.) But if you had used var
instead of let
, yes, it would show up as a property of the global object (which you can access as window
) in a browser.
How to access module global varibales in Node.js
There is no built-in mechanism. NodeJS runs your code within a module scoping function, and so variables you declare at the top level of that code are not globals, and are not automatically added to any accessible object.
If you want them accessible on an object, you'll need to use an object explicitly:
let locals = { // or even `const locals = {` since you won't change the object, just its properties
foo: 3,
bar: 35
};
(In loose mode it would be possible to then use them without an explicit reference to locals
, but I recommend always using strict mode, and recommend not using said mechanism (the much-maligned with
statement) even if you're in loose mode. with
is much-maligned, and disabled in strict mode, for a reason. :-) I mention it only for completeness.)
For true globals, you could use NodeJS's global
global, but of course it's generally best to avoid global variables.