Now is the time. I can't go forward if I don't talk about closures. What are closures? Closures are your friend. That's the first thing you need to know about them. They will help you keep your code clean, healthy and easy.

A closures is created every time you create a function in a function (they are also created in other situations too but I won't talk about them now). When using a closure, you will have access to all the variables defined in the parent function (and all its parent functions too).

Attention! Before reading this article, you should take a look at 3 ways of creating functions in javascript.

Write your first closure

function function1() {
      var var1 = 1;

// Magic here! I create a function inside another function
  function function2() {
      var var2 = 2;
      // I have access to var1 defined in function1
      //(the parent function of the current one)
      alert(var1 + var2);
  // Call function2


// Call function1 (should alert 3) function1();

For the moment, it doesn't make sense but you will surely find a handy way of using it.

Example of a closure

Example of a closure, I want to alert the ID of the timer (returned by window.setTimeout) after 1 second.

In an old-fashioned (without closures) way, I would do the following.

var globalTimer = null;
  function createTimer() {
      // I create the global timer
      globalTimer = window.setTimeout(alertTimerId, 1000);
  function alertTimerId() {
      // Alert the global timer ID
      alert("The timer ID is " + globalTimer);

There are many problems with that code. The most obvious one is : it uses a global variable. You never know what happens to global variables between the time it is instantiated and the time it is used. It's bad.

In a new-fashioned (with closures) way, you would do this.

function createTimer() {
      // I create an inner-function that alerts the timer ID
      function alertTimerId() {
          // I call the "timer" variable from the parent function (using closures)
          alert("The timer ID is " + innerTimer);
      // I create the timer
      var innerTimer = window.setTimeout(alertTimerId, 1000);

I have solved the global variable problem.

Now, what can I do?

Because closures are not implemented in every programming language (update : though it is not specific to javascript), you'll have to try it for yourself. I don't want to give you recipes on how/when to use it, it's up to you. But I could say that a great ajax web2.0 application normally uses a lot of closures.

Keep in mind that - Closures are created everytime you create a function in a function - Closures give you access to variables that are defined in the parent function (and all of its parents) - A closure keeps a reference to an object, not a copy (more on that later) - Watch out for memory leaks in Internet Explorer!!!

comments powered by Disqus