Open In App

Global and Local variables in JavaScript

Global Variable

These are variables that are defined in global scope i.e. outside of functions. These variables have a global scope, so they can be accessed by any function directly. In the case of global scope variables, the keyword they are declared with does not matter they all act the same. A variable declared without a keyword is also considered global even though it is declared in the function.

Local Variable

When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. Accessing them outside the function will throw an error



How to use variables

Example 1: In this example, we will declare variables in the global scope so that they can be accessed anywhere in the program.




let petName = 'Rocky' // Global variable
myFunction()
 
function myFunction() {
    fruit = 'apple'; // Considered global
    console.log(typeof petName +
        '- ' +
        'My pet name is ' +
        petName)
}
 
console.log(
    typeof petName +
    '- ' +
    'My pet name is ' +
    petName +
    'Fruit name is ' +
    fruit)

Output

string- My pet name is Rocky
string- My pet name is RockyFruit name is apple

Explanation: We can see that the variable petName is declared in the global scope and is easily accessed inside functions. Also, the fruit was declared inside the function without any keyword so it was considered global and was accessible inside another function. 

Example 2: In this example, we will declare variables in the local scope and try to access them at different scopes.




myfunction();
anotherFunc();
let petName;
function myfunction() {
    let petName = "Sizzer"; // local variable
    console.log(petName);
}
function anotherFunc() {
    let petName = "Tom"; // local variable
    console.log(petName);
}
console.log(petName);

Output
Sizzer
Tom
undefined

Explanation: We can see that the variable petName is declared in global scope but not initialized. Also, the functions are accessing the inner variable where each function has its own value for the variable petName.

Where to use which variable

Note: Use local variables whenever possible. Always use the var keyword to declare a new variable before the variable is referred to by other statements.


Article Tags :