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.
From function: GFG 12 From block: GFG 12
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.
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.
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).
Please Login to comment...