Before you start throwing things this way, hear me out. A few years ago, no one ever talked about closures in JavaScript. They were a footnote to JavaScript, mostly discussed by people like Douglas Crockford on the Web. Since Ajax has become the focus of everyone’s life, closures have been talked about more and more, leading to some very powerful JavaScript solutions. The problem here is maintainability.

The more closures you use in your code, the more difficult it becomes for other people to understand it, and the more memory you use (let’s not even talk about the infamous Internet Explorer memory leaks). Take a look at some hardcore closure examples and see how long it takes for you to track down which variable is declared where and how it is used.

In my opinion, there’s only a handful of times when closures should be used. If you are using closures to hide variables or create “private” and “priveleged” methods, then you are writing unmaintainable code. The simple fact is that private variables are not a necessity in JavaScript. If you are building an API, your public methods are the ones you document; your private methods are the ones you don’t. Unlike compiled languages, anyone can go into your code at any time and figure out exactly what it’s doing, so why bother trying to hide properties and methods from other developers?

If you are writing JavaScript code for a company, you have a duty to make sure your code is maintainable and scalable long after you are gone. You do this by avoiding closures and making your objects and their relationships very clear. You may think you’re being smart using closures, but all you’re doing is making the code unnecessarily complicated and that much more difficult to understand. Closures are akin to misdirection in magic: you make people look in one direction while pulling a quarter from behind their ear. It’s cute, and sometimes brilliant, but there is no value when your main goal isn’t trickery.

So I implore all JavaScript developers working for various companies around the world, do yourself and your coworkers a favor: next time you think about using closures to alter scope or change the visibility of a property/method…don’t

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.

Both comments and pings are currently closed.