How JavaScript Closure Work? Explain with Examples

This post will explain you the concept of closures in JavaScript. Programmer better understand the concept of closures after read this post, that it is not difficult and conceptual. Closures help JavaScript programmer to write organize code, no matter you are hard core JavaScript programmer, you can easily use it again and again. I again say that closures are much easily to understand and repeatedly use for your daily JavaScript tasks.

What is JavaScript Closures Actually Means?

A closure is an inner JavaScript function which has access outer JavaScript function’s variables called Scope Chain. JavaScript closure three variable scope chains which have access to its own scope variables, it also has access to the outer JavaScript function’s variables and then access to the global variables. Inner function not only has access to the outer variables, but also has access to the outer function’s parameters.When a particular function start execution a closure is allocated the function, and it remain in the memory when a function returns wherever it called.

Example 1.

In this example function access the variables which are define outside the function. Here is the code of JavaScript function.

var a = 4;

function myFunction()

{ return a * a; }

Example 2.

Here is a good example that shows that local variables are not copied and they are kept by its reference. The function keeping stack frame in memory whenever outer function exits.

function abc77() { // Local variable that ends up within closure

var num = 42;

var say = function() { console.log(num); }

num++; return say; }

var sayNumber = abc77();

sayNumber(); //

Example 3.

In this piece of code you can see that three global JavaScript functions have a ordinary reference to the same closure which declared in a single call setupSomeGlobals().

var gLogNumber, gIncreaseNumber, gSetNumber;
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 42;
// Store some references to functions as global variables
gLogNumber = function() { console.log(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }

gLogNumber(); // 43
gLogNumber(); // 5

var oldLog = gLogNumber;

gLogNumber(); // 42

oldLog() // 5

Whenever you call setupSomeGlobals() function the new closure is created and old variables are override with in new function call. In this example old variables gLogNumber, gIncreaseNumber and gSetNumber are override.

I think after reading the post you will have better understanding of JavaScript closures and it use, yes off-course it is wide rang of examples are available on the internet but I add the best an easy examples to JavaScript programmers.

About Moazzam Qureshi

I am SEO expert and web developer since 2011. My hobby is to write & provides quality content about blogging, SEO , Social Media , Earn Online and Affiliate Marketing.

Leave a Reply