JavaScript Guide – Everything You Need To Know About Variable Scope

Posted by TotalDC

Scope of a variable is the part of the program from where the variable may directly be accessible.

In JavaScript, there are two types of scopes:

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

Let’s say you have global variable defined in first line in 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 are able to 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 global variable, but console.log with local variable gets you an error. This is because now the console.log statement are present in global scope where they have access to global variables but can’t access the local variables. Also worth noticing 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 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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: