JavaScript: Closures

JavaScript: Closures

This is the second part of the post on JavaScript core concepts series. In this post, we will look into JavaScript closures.

Closures

Whenever you create a function, JavaScript creates a local scope of all its parameters and variables available within that function. This means all parameters and variables are available only for that function declaration and not outside of it. This act is called closure. So if you would like to encapsulate any variable exposure to global scope, closure is what you are looking for. Let's have a look at closure with this code.

function closeMyVariablesAndParams(param) {
	var foo = "Hello " + param;
    
	console.log(foo); // prints Hello codesips
}
closeMyVariablesAndParams("codesips");
console.log(param); //Error: param is not defined
console.log(foo); //Error: foo is not defined

It also means, no matter how deeply nested they are, the child function will have access to all of its parents' variables and parameters but not the other way around.

var globalScopedVar = "I am globally available";

function grandParentFn() {
	var grandParent = "I'm available to myself also to all my children";
    
	function parentFn() {
		var parent = "I'm available to myself also to all my children";
        
		function childFn() {
			var child = "I'm only available to myself";

			console.log(globalScopedVar); //Prints
 			console.log(grandParent); //Prints
			console.log(parent); //Prints
			console.log(child); //Prints
		}
	}
}

As you can see, every time you create a function JavaScript creates a local scope for your function and this behaviour is called closures.

Show Comments