JavaScript Variable Scope

There are two variable scopes in JavaScript: local and global. Local variables exist only inside the function in which they were declared. Local scope means a variable can only be referenced from within that function in which it was declared. Global variables, on the other hand, once declared, exist throughout the script and their values can be accessed (and changed) from within any function or outside of a function. In other words, global scope means a variable can be referenced from anywhere within your site’s javascript.

There is a third type of scope called "static" or "closure". "Closures" are variables that are local to a function, but keep their values between function calls. Closures are an advanced javascript topic and will not be discussed in this article.

Let’s show 5 variables being declared, and discuss their scope

1.  <script type="text/javascript">
2.   
3.  var outsideFunction1 = "hello"; 
4.  outsideFunction2 = 42; 
5.   
6.  function myFunction(myParameter){
7.      var insideFunction1 = new Array();
8.      insideFunction2 = false;
9.  }
10.   
11. </script>

Listing 1: Example of local and global variable declaration

The first variable is on line 3: outsideFunction1. Even though this variable is declared with the var keyword, it is declared outside of any function, and therefore has global scope.

The second variable is on line 4: outsideFunction2. This variable is also declared outside of any function, and therefore has global scope.

The third variable is on line 6: myParameter. Function parameters always have local scope. Even if there were a global variable called myParameter, that global variable will maintain its value even if the value of myParameter was changed within the function.

The fourth variable is on line 7: insideFunction1. Because this variable is declared within a function with the var keyword, it also only has local scope. Similar to parameter variables, even if there were a global variable called insideFunction1, that global variable would maintain its value even if the value of insideFunction1 were changed within the function.

The fifth variable is on line 8: insideFunction2. This is really the reason that this article is needed: this is a global variable declared within a function, which is one of the most common causes of logic errors. Because the var keyword has been omitted, the insideFunction2 variable is global.

Local Variables

Variables initialized inside a function using the var keyword will have a local scope. If you initialize a variable inside a function without the var keyword, your variable will have a global scope. Parameters are local variables, as if the keyword var was included before the parameter. Local variables, including a parameters, can have the same name as a global variable.

var myName = "estelle";  // global
alertThisName("jonathan");
 
function alertThisName(myName){ // local
		alert(myName); // alerts "jonathan"
}
 
alert(myName); // alerts "estelle";

Listing 2: The variable myName is declared both globally outside of the function, and locally as the function parameter. Variables declared as function parameters have local scope. The myName variable on the first line is a global variable. The variable myName declared as a parameter of the function is a local variable only visible within the alertThisName function.

In this case, declaring a local variable with the same name as a global variable masks the global variable: all global variables in your script are accessible to this function EXCEPT the global myName variable.*

Note: In browsers, global variables that are masked by a function’s local variable with the same variable name are still accessible to the function by accessing the global variable thru it’s parent. In Listing 2, if you are in a browser, you could access the global myName variable from within the alertThisName function by using window.myName or top.myName.

var myCount = 7;  // global
doSomeMath();
 
function doSomeMath(){ // 
		var myCount = 7 * 7;
		alert(myCount); // alerts "49"
}
 
alert(myCount); // alerts "7";

Listing 3: In this example, the global and local variables both have the same name. Since the variable within the function was declared using the var keyword, the variable has local scope. Manipulating the value of the local value has no impact on the value of the global variable declared in the first line.
Once we exit the function, the local variable myCount no longer exists and recognition of the global variable’s existence is reinstated.

Similar to listing 2, in this case the local declaration of the myCount variable makes the global myCount variable inaccessible to this function. The function can access all global variables EXCEPT for the global myCount variable, unless you access the variable as noted in the tip above.

var myCount = 7;  // global
doSomeMath();
 
function doSomeMath(){ 
		myCount = 7 * 7;
		alert(myCount); // alerts "49"
}
 
alert(myCount); // alerts "49";

Listing 4: Since the variable within the function was declared WITHOUT using the var keyword, the variable has GLOBAL scope. The global variable declared in the first line and the variable used in the function both have the same name and are, indeed, the same global variable. In this example, manipulating the value of the global value within the function changed the value of the variable throughout the program.

function doSomeMath(){  
		myCount = 7 * 7;
		alert(myCount); // alerts "49"
}
 
alert(myCount); // throws an error: myCount is undefined

Listing 5: While the variable in the doSomeMath function would be a global variable, as the variable is declared in the function WITHOUT using the var keyword. Since the function is never called, the variable is never declared. Accessing the variable that doesn’t exist in the last line throws an error.

Rules to remember:

  1. Local variables inside a function can only be referenced from within the function in which the local variable was declared.
  2. All global variables can be referenced from within any function.
  3. All global variables can be referenced from outside any function.
  4. No local variables, declared with use of the var keyword, can be referenced from outside the function in which they were declared

Published by

Estelle Weyl

My name is Estelle Weyl. I an open web evangelist and community engineer. I'm a consulting web developer, writing technical books with O'Reilly, running frontend workshops, and speaking about web development, performance, and other fun stuff all over the world. If you have any recommendations on topics for me to hit, please let me know via @estellevw.