Saturday, 7 December 2024

Global variables in JavaScript

Global variables in JavaScript are variables that are accessible throughout the entire script or application, regardless of where they are declared. They can be accessed and modified from any part of the code. Understanding global variables is crucial, especially in larger applications, where their improper use can lead to issues like unexpected behavior, conflicts, and difficulty in debugging.

How Global Variables are Created?

Declaring Variables Outside Any Function

When a variable is declared outside of any function using the var, let, or const keywords, it becomes a global variable.

var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global and constant";

function checkGlobal() {
    console.log(globalVar);
    console.log(globalLet);
    console.log(globalConst);
}

Variables Declared Without var, let, or const

If a variable is declared without the var, let, or const keywords inside a function, it automatically becomes a global variable.

function makeGlobal() {
    globalVarWithoutKeyword = "I am global without var, let or const";
}

makeGlobal();
console.log(globalVarWithoutKeyword);

Find the below working application.

 

globalVariablesCreation.js

var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global and constant";

function checkGlobal() {
    console.log(globalVar);
    console.log(globalLet);
    console.log(globalConst);
}

checkGlobal();

function makeGlobal() {
    globalVarWithoutKeyword = "I am global without var, let or const";
}

makeGlobal();
console.log(globalVarWithoutKeyword);

Output

I am global
I am also global
I am global and constant
I am global without var, let or const



 

However, if you declare a variable using let or const, it does not become a property of the window object.



Points to consider while using global variables

1.   Global variables can be unintentionally overwritten by other parts of the code or by external libraries.

 

2.   Using global variables can lead to tight coupling between different parts of the application, making the code harder to maintain.

 

3.   Global variables remain in memory for as long as the application is running, which can lead to higher memory consumption.

 

4.   Tracking the usage and modification of global variables across large codebases can be challenging, leading to bugs that are difficult to trace.

 

5.   Avoid using global variables as much as possible. Prefer using function-scoped or block-scoped variables with let and const.

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment