Closures

Thick-headed imbecile that I am, I’m finally beginning to understand some stuff. I think I understand closures now—just a little bit. Re-learning things I though I already knew is hard…

I’m currently playing around a little bit with Javascript—a language weirdly powerful enough to make me re-think my programming style, but not too different from the standard C/C++/Java stuff that I get scared away. I’m also learning Scheme, watching those SICP lectures, although I’ve not started working on real-ish projects with Scheme. I’m hoping that Javascript turns out to be a sort-of bridge language for me.

Here’s the thing: a closure is just a function that remembers its environment. Simple, once I understood it.

Look at this ‘toy’ example:

function getToggler() {
  var status = false;
  return function() {
    status = !status;
    return status;
  }
}

And here’s how to use it:

>>> t = getToggler()
function()
>>> t()
true
>>> t()
false
>>> t()
true

The getToggler() function is a function that returns us a toggle function. Constructs one, you could say. Now, functions that return functions may seem weird at first, but on getting used to the idea, it’s an indispensable means of abstraction.

The variable status is bound to this newly created function. Variables created inside ordinary function die as soon as the function is executed, but the variable status in this case lives on as long as the returned function is alive. The ‘result’ of the getToggler calls will remember it’s status.

And no, these are not shared variables. Each time you get a new toggler, it is bound with a separate state.

Once you get your head around this, closures are a powerful concept. And pretty basic, I can’t believe it took me so long to grok them.

Abstraction is a powerful tool. Why write a function for every case, when you can write a function that will generate a function for any given specific case? I’m just starting to learn.

Comments (2)

  1. Nandish wrote::

    Hmm, sounds pretty interesting.. though confusing the first time u read it.

    Saturday, March 31, 2007 at 13:34 #
  2. Sunil wrote::

    Thick headed imbecile…….. hmmm….
    Bingo!!!

    Friday, April 6, 2007 at 22:38 #