Open In App

Why to avoid global variables in JavaScript ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Global variables are variables that are declared or defined outside any functions in the script. This indicates that global variables can be accessed from anywhere in the particular script and are not restricted to functions or blocks. JavaScript global variables can also be declared from within a function or block and then can be accessed from anywhere as mentioned earlier. The window object is used for this exact purpose.

Example 1: Defining a global variable and using it in a function and a block and also defining a global variable within a function by using the window object and using it in the same function and block, indicating the global scope of both variables.

Javascript
// Global variable 'a' declared and assigned 
const a = "GFG";

// Global variable 'b' declared
let b = 12;

// Function to set the global variable 'b'
function geeksForGeeks() {
    b = 12;
}

// Function to access global variable 'b'
function geeks() {
    console.log("From function: " + b);
}

geeksForGeeks();
geeks();

// Global variable 'b' can be used in this block as well
{
    console.log("From block: " + b);
}

Output:

From function: GFG 12
From block: GFG 12

Explanation: The first example gives an idea of the typical ways in how global variables can be created and then used or accessed in JavaScript. The variable a is defined in global scope in the script using the traditional syntax. On the other hand, the variable b is declared and assigned a value with the window object. The application of this object is necessary due to the fact that b is declared inside a function hence it has function scope by default and the window object converts it to the global scope.

Upon first glance, it might seem that global variables are easy to use and are more convenient than using local functions and block-scoped or local scoped variables. But the truth is that the use of global variables should be minimized as much as possible. This is because once a global variable is declared, it can easily be modified by any successive function or block defined within the script, or multiple scripts, and any variable name can be misspelled by mistake, resulting in debugging issues especially for large codebases. 

To combat this, it is always recommended to use local variables wherever possible. Now multiple functions or blocks can have variables defined locally with the same name and not cause any conflicts, which in turn leads to a low chance for errors.

Example 2: Creating a local variable with local scope within a function and also creating a local variable with the same name as the previous local variable within another function. This ensures there are no conflicts in multiple variables with the same name defined in the script.

Javascript
function GFG() {
    var localVariable = 12; // Local variable
    console.log("Local variable:", localVariable);
}

function geeksForGeeks() {
    // Local variable with same name, different value
    var localVariable = "Geek";
    console.log("Local variable:", localVariable);
}

// Function call
GFG();
geeksForGeeks();

Output:

Local variable: 12
Local variable: Geek

Explanation: The second example illustrates the utilization of local variables with the same name but different values in different functions. If a global variable would have been used here, then the second variable with the same name would have had the same value as the first variable due to global scope as opposed to local scope which is not the desired behavior in this example. This is why local variables should be used wherever possible as mentioned earlier.

Example 3: This example demonstrates a solution or workaround to using global variables in JavaScript. It involves wrapping the whole script in a closure function and then the variables which need to have global scope can be manually exposed.

Javascript
(function () {
    var myVar = "GFG";
    console.log(
        "This is within the closure function"
    );

    // Manually exposing the variable to global scope
    this["myVar"] = myVar;
})();

console.log("Global variable:", myVar);

Output:

This is within the closure function
Global variable: GFG

Explanation: The third example shows an alternate way of representation of global variables but without the aforementioned drawbacks using closure functions. The variable which needs to have global scope can be manually exposed using the window[“var_name”] = var_name syntax. Still, it is recommended to avoid the usage of global variables as much as possible and instead use function scoped or block-scoped variables (local scoped).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads