-3

On this page:

I found that it is important to use var and we can not use let and const for declaring global variables and functions but I tried to do use let and const. So should I use them or they are not recommended?

Here is my code that I ran:

let a;
globalThis.a = 3;
console.log(globalThis);

and here is the output:

enter image description here

So you can clearly see a gets added without any error. So should I continue using this or this works but not recommended?

1 Answers1

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ernesto Stifano
  • 3,027
  • 1
  • 10
  • 20
  • I diidnt understood the first part related to module but i will undersrant it when i learn modules but I udnerstood the second part that var should not be used and I thank you for the answer – Tushar Vaswani May 21 '21 at 12:01