Best Jquery ,javascript, HTML5 CSS3 tutorial with jquery examples, php script , demos for beginners, web designers and web developers.

Jquery

Jquery, javascript Training

Jquery training blog

What is JavaScript Closures

In JavaScript closures are objects that contains a function which bound by reference to the environment in which the function was created.closures makes a function to have private variables.

Examples will make it clear.

In javascript variables has local or global scope. So to make global variables local JavaScript closures will make it clear.

A function can access all variables defined within that function.

function expFunction() {
    var x = 5;
    return x * x;
}

But a function can access variable defined outside of the function.

 var x = 5;
function expFunction() {
    return x * x;
}

In the first example x is local and in second example x is global.

Local variable works only within the function if the function is called then it will work. Out side the function local variable has no existence

On the other hand global variables are available throughout the web page. Any function can access the global variable.

See below example.

var total = 5;

function incrementCounter() {
    total += 5;
}

incrementCounter(); Out put -> 10
incrementCounter(); Out put -> 15
incrementCounter(); Out put -> 20

On calling the incrementCounter() it will increase the total; But apart form call of function incrementCounter() any other function can increment the total variable. So how to prevent the total to stop increment total? If you define the total variable within the incrementCounter() function no other function can increment it outside incrementCounter() function.
Now another problem arise if we call incrementCounter() function as below what it would be the output

incrementCounter() Out put -> 10

incrementCounter() Out put -> 10

incrementCounter() Out put -> 10

So what we have seen in the above example total is not increasing.

Now we can call self invoke function in it it will solve the issue


var incrementCounter = (function () {
    var total = 5;
    return function () {return total += 5;}
})();

incrementCounter();
incrementCounter();
incrementCounter();

And this is called

JavaScript closures

Please follow and like us:





Got Something To Say:

Your email address will not be published. Required fields are marked *

*


About the author

Joydeb Choudhury holds a Master's degree in Computer Application from I.G.N.O.U. After working as a web developer in various companies he has started bloging in 2016.

Recent Posts of blog

Downalod Free Php Scripts