Variable Scope

Contact Us or call 1-877-932-8228
Variable Scope

Variable Scope

Variables in JavaScript are declared with the var keyword and are either globally or locally scoped.

A variable is globally scoped if any of these conditions are met:

  1. It is declared outside of a function.
  2. It is used without being declared using the var keyword.

A variable is locally scoped if it is declared within a function using the var keyword.

Global variables are accessible from anywhere within your JavaScript code.

Code Sample:

AdvancedTechniques/Demos/variable-scope.html
---- C O D E   O M I T T E D ----

	var maxNum; //global
	function prepare() {
		var maxNum = 5; //local to function
		//let's forget the "var" in the "for" declaration
		for (i=0; i <= maxNum; ++i) { //no var, so i will be global
			//do something
		}
	}
	
	prepare();
	alert(maxNum); //undefined
	alert(i); //6 (because it is globally scoped)
---- C O D E   O M I T T E D ----

Notice that maxNum is declared globally but not assigned a value. It is also declared within the prepare() function and assigned the value of 5. When we read the maxNum value after calling prepare(), we see that the value is undefined. That's because it's reading the global variable. We can't access the function variable from outside of the function.

We can access the i variable though. That's because we assigned a value to it within the function without declaring it using var.

JavaScript does not have block scope, so variables are never local to an if statement or a for loop.

Next