JavaScript closures make my head spin

Coming from a world of strongly typed programming languages, JavaScript is weird. And the deeper I get, the weirder it got.

I’ve had brushes with JavaScript closures in my learning to date, and the fragments I saw looked like evil black magic. Today I dove in headfirst to learn more about it.  With my new found knowledge, it no longer feels like black magic.

It still feels evil, though.

Closures have all the appearance of something that “fell out” of the flexibility of the JavaScript type system. It felt like somebody, in an effort to solve some unrelated problems A, B, and C, accidentally opened a Pandora’s Box and closures emerged. With some bizarre behavior and huge potential for difficult-to-diagnose bugs. I’d hate to think it was designed to be that way. I prefer to believe it was an accident.

Accident or not, it is a very powerful mechanism and people are using it in the world. Which means I will need to be able to read and understand code that uses closures. It is irrelevant whether I personally believe closures are evil.

It’ll take a few more rounds of practice before I’m comfortable with the nuances. In the meantime, I’ll be reviewing this page frequently as I found it to be the most helpful. The author emphasized repeatedly that hands-on experience with real closure code is more illuminating than reading a lot of rigorous academic style description of closures. So that’s exactly what I intend to do.

 

The best I can hope for is to start feeling comfortable with the power and pitfall of closures. Maybe I’ll even come to appreciate it as a necessary evil.

But I doubt I’ll ever come to think of it as A Good Thing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s