What make JavaScript closures work?

submit to reddit

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.

Related posts:

  1. JavaScript closures in brief
  2. OOP JavaScript: Accessing Public Methods in Private Methods
  3. Object Oriented JavaScript: Inheritance

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in javascript, micro tutorial and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to What make JavaScript closures work?

  1. derek masa says:

    no idea

  2. derek masa says:

    it’s something functional i guess

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">