What is Javascript Variable Scope

In the Javascript variable scope, means the lifetime of a variable i.e where the variable is visible and where it is available for us to use in our code. In JavaScript, we have not many but just a couple of different types of scopes.

Javascript variable scope types

In Javascript, we have three types of variable scope.

  1. Gobal scope
  2. Function scope
  3. Block scope

When we are learning the programming language, each language has its own variable scope. Understanding variable scope in a particular language is very important, in designing software, we need to have higher cohesion and less coupling among code.

The ES6 has introduced two new keywords for declaring variables, let and const. In Javascript, we have a three-way of declaring a variable.

  1. var
  2. let
  3. const

In Javascript, everything is data, even function, and objects are also variables. Based on where the variable is declared that determines the Javascript variable scope and we can declare the variable at any place in the code as.

  • Inside block statement { … }
  • Inside function
  • Inside loop, special on for loop using of var keyword make it accessable outside loop.
  • Inside object
  • Outside any function, which make is as Javascript gobal variable.

Javascript variable scope 1: Javascript Global variable

When the variable is declared outside of any function or at the top level of the program, then it becomes a global variable and can be accessed from anywhere in the code. We can declare global variables using var, let, and const.

Any variable declared outside any function with var, let and const keywords are a Global variable, has a global scope, and is accessible everywhere. Example of Javascript Global variable when it is declared at the top level of the program.

Javascript variable scope
Javascript global variable

In this example, we had declared num at the top level of programming or it is not within any block. Thus variable num becomes a global variable, now we can access it anywhere in our program. The num is first initialized as 10, then it is accessed in incrementNum function and increment its value by one. At last, it is printed outside, in console.log its value is 11.

Warning: Try to avoid using global variables, until it is really necessary. Using Javascript global variables is not good practice and there is the chance of side effects and possibility to introduce errors by accident.

Javascript global variable example two where we declare total outside any function.

function sumNums(num1, num2) {
   total = num1 + num2;
};

let total = 0;

sumNums(20, 30);

console.log(total); //Output 50

Automaticaly Global variable

When we assign a value to an undeclared variable in Javascript then JavaScript by default creates that variable on the global object:

Javascript variable scope example

Even we had a variable name inside a function, when we assign the value ‘Edupala’ to undeclare variable name, it becomes a Global variable and can access from anywhere.

Warning : Be careful on assigning value to undeclare variables and assigning value to it become global variable regardless of its location.

Javascript Function scope

When a variable is declared inside the function it has a Javascript function scope, just like a function parameter. The function scope variable is only visible and accessed within the function where it was declared. This variable dies when the function task is completed.

The var variable declaration is traditionally function scoped and we can define Javascript function scope using all three, that is var, let, and const. All of its declarations should be within a function.

function calculateTax(amount) {
   const tax = amount * (0.016);
   console.log(`Tax of ${amount} : ${tax}`); // Tax of 40000 : 640
}

calculateTax(40000);

console.log(tax); //Uncaught ReferenceError: tax is not defined

Important to note

  • Variable tax is declare with const keyword inside function and we can’t access it outside this function. Accessing tax outside function will generate error Uncaught ReferenceError: tax is not defined. As scope of tax is at function level.
  • If we didn’t add const keyword on tax, then undeclare variable become global, then we can access it outside this function.

Javascript Block scope

Both let and const keyword variable declaration provide Javascript block scope. The var keyword is traditionally function scoped. In Javascript, we can declare block scope within the opening and closing curly brace {}.

We can define the block-level scope in loop, function, switch, if and else, and any use of {} curly brace create block scope. The variable can’t access outside of the particular {} block. Example of Javascript block scope.

javascript block scope example

We had declared sub variable with const, both sub in if and else are different. Accessing the sub variable outside of its block will generate an error as shown above.

Careful of using var in for loop

Javascript does not implement var keyword as block scoping. When we use the var keyword in for loop, then it is not blocked scope, and it becomes functional scope. In the example below we had used the var keyword on for loop to declare a variable i.

function scopeTest() {
   for (var i = 0; i <= 5; i++){
     inFor = i; 
   }
  console.log("Value of inFor" +inFor);  // Output 5
  console.log("Value of i" +i); // Output 6
}

The output of the above code inFor as 5 and i as 6.  The new version of Javascript allows us to use a new keyword called let to achieve block level in the loop. Variables declared with let inside a block scope are only accessible inside that scope. If we use let to declare the i variable in a for loop, that variable will only be available inside the for a loop.

The scope of variables declared using var is within the function it is defined and global if it is not defined inside any function, while the scope of let is restricted to within the enclosing block it was declared in and global if it is not defined inside any enclosing block.

function scopeTest() {
   for (let i = 0; i <= 5; i++){
        inFor = i; 
   }
   console.log("Value of inFor" +inFor);  
   console.log("Value of i" +i);
} 

For the above code output value of in For is 5 and we can’t access the i value outside so it will generate an output message as Uncaught ReferenceError: i is not defined.

Lifetime of Javascript variable scope

The variable has a lifetime, it starts when a variable is declared, but the end is different for each scope.

  • Global scope: Variable stay or accessible until browser window or tab is closed.
  • Function scope: Variable die when function is completed.
  • Block scope: Variable die when block statement is completed.

Conclusion
We had a complete discussion on Javascript variable scope and always try to avoid using Global variable declarations unless it is really needed. Try to use let and const to declare variables that will limit the scope of variables which in turn avoid polluting our code. Never use var, as is old fashion and (let and const) are replacement of var keyword.

Related posts

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top