JavaScript closures

I like JavaScript! There, I said it!

I work in a JavaScript hostile environment where people want to do everything in pure Java, which is why I spend most of my time trying to get JSF and a Portal server to play together nicely (sad story!). But! Deep down I long for a simpler life, a life consisting of HTML, CSS and pure JavaScript and nothing else (well maybe a bit of PHP on the server).

So why do I like JavaScript? I like it because it’s so dynamic. Need a method on an object? Just add it when you need it. You can bend the rules and pretty much do as you please. More than once has JavaScript saved our arse when normal server side programming has failed. And then there’s the more “hard to grasp when you’re used to Java” features. Things like that a function can return a function, callback functions, scope of variables and closures.

Especially closures I’ve had quite a few attempts at trying to understand. I’ve been attending a JavaScript course recently which was very interesting and fun. Of course we were discussing closures and this time I think it finally clicked. Therefore, to remember, I’ll write this post, so that I can re-read it in six months when I’ve forgotten about closures again.

Continue reading JavaScript closures