Tag Archives: Closure

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.

Firebug’s console.profile vs console.time

Firebug’s console.time!

This post is directly related to the previous post where I explain how to use the Firebug’s console object and in that case its time method. That is really powerful and gives the opportunity to track the performance of a sample JavaScript chunk of code. What it does not do is to give you a more detailed profile of that particular JS code.

That’s because the console’s profile method works on functions and if you’d like to profile a loop it will give you there’s nothing to be profiled. One workaround to that is to use closures.

JavaScript closures

A JavaScript closure is to make an anonymous function and to put the code in it, like so:

(function() {
 for (var i = 100000; i--; ) {
  var a = new Array();
 }
})();

Firebug’s console.profile()

That code can be than wrapped with both console.profile() and console.profileEnd() in something like:

console.profile('my profile');
(function() {
 for ( var i = 100000; i--; ) {
  var a  = new Array();
 }
})();
console.profileEnd('my profile');

That will give a more precise measurement like that one shown on the picture bellow:

firebug console.profile