Global Variables in Modules

In JavaScript any variable that is declared outside any function or block is said to be in global scope and that variable is called global variable. The Global Object provides variables and functions that are available everywhere. It is named window in browser and global in Node.js and have different names in different environments.

Global Variables in Browser

In a browser, global functions and variables are declared with var to make it a property of the global object. For example:

1
2
3
4
5
6
7
var global=5;
var globalFunction =function(){
console.log(10);
}

alert(window.global); //5 (became a property of window object)
window.x(); //10

If let was used, it wouldn’t become property of the global object

1
2
3
let global=5;

alert(window.global); //undefined (doesn't become a property of window object)

Global Variables in Node.js

In Node.js, any variable declared outside any function has only file scope. Each individual file has its own global scope. Modules are files that contain a class or a library of functions for a specific purpose. Modules can load each other and use special directives import and export to interchange functionality. Each module has its own top-level scope and any global variables are in the files are actually visible to the particular file only.

What happens to the global variable in a module, if the module is imported?

When a module containing a global variable is imported to another file, the variable itself is not passed to the file. Only the specified functions are imported to the file. If the specified functions use global variables in their implementation, that value alone is copied and not the whole variable.

In browser, a variable can be made global by explicitly assigning it to a window property. For example:

1
2
window.user= "Harry";
alert(window.user); //Harry

Using global variables is generally discouraged, because it can be modified anywhere in the code and can lead to errors. Also, debugging code is clearer, much less prone to errors and easier to test when global variables are not used.