Skip to content

Scope, Nested Function and Closure

PhoenixAndMachine edited this page Apr 7, 2014 · 1 revision

Scope, Nested Function and Closure

Variables can be called global variables, local variables, or others according to their scopes. In Javascript, it has very interesting issues with scope.

  1. Javascript has function level scope. This means a variable defined within a function is not accessible outside of it.
  2. Javascript has lexcially level scope. This means functions run in the scope they are defined in, not the scope they are excuted in.

In this example, we define a nested the function in an anonymous function.

/* An anonymous function used as closure */
var baz;

(function() {
	var foo = 10;
	var bar = 2;
	baz = function() {
		return foo*bar;
	};
})();
/* 
function level scope
*/
try {
	console.log(foo); 
}
catch(err) {
	console.log(err); // [ReferenceError: foo is not defined]
}
try {
 	console.log(bar); 
}
catch(err) {
	console.log(err); // [ReferenceError: bar is not defined]
}
/*
lexcially level scope
*/
console.log(baz()); // 20

The scope of JS is very important when defining class with access control, since there are no keywords private, public in Javascript.

Clone this wiki locally