Global and local variables in JavaScript

Global Variable: These are variables that have global scope, meaning they are defined outside the function. These variables have global scope, so any function can access them directly. For global scope variables, the keywords used in the declaration are not important; they all behave the same way. Variables declared without keywords are considered global even if they are declared inside a function.

Local Variable: When using JavaScript, local variables are variables defined within a function. They are locally scoped and can only be used within the function that defines them. Accessing outside the function will result in an error.

How to use variables:

  • The scope of a variable or function determines what code has access to it.
  • Variables that are created inside a function are local variables, and local variables  can only be referred to by the code within the function.
  • Variables created outside of functions are global variables, and the code in all functions has access to all global variables.
  • If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems.
  • In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance of errors.

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

JavaScript

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.

JavaScript

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:

  • Although it may seem easier to use global variables than to pass data to a function and return data from it, global variables often create problems. That’s because any function can modify a global variable, and it’s all too easy to misspell a variable name or modify the wrong variable, especially in large applications. That, in turn, can create debugging problems.
  • In contrast, the use of local variables reduces the likelihood of naming conflicts. For instance, two different functions can use the same names for local variables without causing conflicts. That of course, means fewer errors and debugging problems. With just a few exceptions, then, all of the code in your applications should be in functions so all of the variables are local.
  • If you misspell the name of a variable that you’ve already declared, it will be treated as a new global variable. With this in mind, be sure to include the keyword when you declare new variables and always declare a variable before you refer to it in your code.

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, codeconfig.in Courses are your key to success. We provide top-quality content at no cost, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!