All You Need To Know About JavaScript Variable Scope

Posted by TotalDC

Variable scope is part of the program from which the variable is directly accessible. In This article, we will talk about JavaScript variable scope.

In this article you will learn:

javascript variable scope

What Is JavaScript Variable Scope

In JavaScript, there are two types of scopes:

  • Global Scope – Scope outside the outermost function attached to the Window.
  • Local Scope – Inside the function being executed.

Let’s say you have a global variable defined in the first line in the global scope. Then you have a local variable defined inside the function func().

let globalVar = "This is a global variable";
  
function func() {
  let localVar = "This is a local variable";
  
  console.log(globalVar);
  console.log(localVar);
}
  
func();

When you execute the function func(), the output shows that global as well as local variables are accessible inside the function as we can console.log them. This shows that inside the function you have access to both global (declared outside of the function) and local variables (declared inside the function). But what if you move console.log statements outside the function and put them just after calling the function?

let globalVar = "This is a global variable";
  
function func() { 
  let localVar = "This is a local variable"; 
}
  
func();
  
console.log(globalVar);
console.log(localVar);

You are still able to see the value of a global variable, but console.log with the local variable gets you an error. This is because now the console.log statement is present in global scope where they have access to global variables but can’t access the local variables. Also worth noticing is that any variable defined in a function with the same name as a global variable takes precedence over the global variable, shadowing it.

Where To Use Which JavaScript Variables

  • 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.