I will try to shed some light on this. Generally speaking, regardless of the programming language, environment and use case, it is always good practice to keep variables/data scopes as narrow as possible. This is for many reasons spanning from security to simple namespace pollution and code organization.
I see that you are at the beginning of your JavaScript journey. As you'll start creating more complex applications, you'll find patterns that will almost oblige you to keep your variables local. This is achieved by using function scopes in JavaScript.
In a browser, code outside modules and functions (actually they are the same as you'll see) is considered to be in the global scope, which is anyway always accessible using window
or other syntaxes (self
, frames
, this
sometimes). However, in other environments, like NodeJS, this will not work for two main reasons. The first one is that all the code is executed inside modules. The second reason is that some of the above syntaxes doesn't even exist.
In node, you can use global
to access the global scope. However, variables created, even with var
, will always be local because modules are wrapped inside a function like this:
(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
So, even variables like "exports", "require", "module", "__filename", "__dirname" that seemed global are actually local for each module.
globalThis
was introduced to create a consistent way of accessing the global scope across multiple environments.
Finally, I recommend you to not use var
, but const
and let
and to organize your code in a way that, ideally, no variable is exposed in the global scope.