What make JavaScript closures work?

Closures again

Most of the JavaScript developer don’t even know what a JS closure is and that’s why Crockfrod is so angry. Yes, it’s true, most of the “developers” just copy and paste the code without even know how it works. OK, just in breve the closure is an anonymous function, which thus helps you define a pseudo namespace, as you may know that in a function everything is visible inside it and only there.

function myFunc() {
    var a = 10;
}

The code above makes the variable a to be visible only inside the function. But as you know there must be a function call to make “all this code work”.

myFunc();

However you can make an anonymous function – or a closure, where the function is with no name and is called once the code has been processed. The right syntax is like so:

(function() { var a = 10; })();

Why and how?

The question is: why and how that works? Why this syntax is correct?

Hint

A tiny hint is that you can make the following line working:

var myFunc = function(){ var a = 10; }();

Pay attention to this syntax and the assignment is what makes all this working.

2 thoughts on “What make JavaScript closures work?

Leave a Reply

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