Scope

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

Scope

"Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences.

When a variable is declared inside of a function using the var keyword, it is only available to code inside of that function -- code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to the declared variable.

Furthermore, variables that are created inside a function without the var keyword are not local to the function -- JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have extremely unexpected consequences;

Functions Have Access to Variables Defined in the Same Scope

var foo = 'hello';

var sayHello = function() {
	console.log(foo);
};

sayHello();         // logs 'hello'
console.log(foo);   // also logs 'hello'

Code Outside the Scope in Which a Variable was Defined Does Not Have Access to the Variable

var sayHello = function() {
	var foo = 'hello';
	console.log(foo);
};

sayHello();         // logs 'hello'
console.log(foo);   // doesn't log anything

Variables With the Same Name Can Exist in Different Scopes With Different Values

var foo = 'world';

var sayHello = function() {
	var foo = 'hello';
	console.log(foo);
};

sayHello();         // logs 'hello'
console.log(foo);   // logs 'world'

Functions can See Changes in Variable Values After the Function is Defined

var myFunction = function() {
	var foo = 'hello';

	var myFn = function() {
		console.log(foo);
	};

	foo = 'world';

	return myFn;
};

var f = myFunction();
f();  // logs 'world' -- uh oh
Next