Monday, February 21, 2011

Important Concepts in Javascript: Closures

The other day I asked "What are the most important javascript concepts to know for a job interview?". The most common answer was Closures so I figured I would google it. From wikipedia:
In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

I know, wha? I think after a few hours on wikipedia I think I finally came up with a code snippet that illustrates that statement.

Still confused? I think mozilla explained it the best:
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

A closure lets you associate some data (the environment) with a function that operates on that data.

Ok so why do I care?
Well if you have ever done any web programming in javascript you have probably been using this for years without even knowing it. Lets take a look at binding a click event in jQuery:

Also if you have ever created a javascript objects using the module pattern:

Closures are something that javascript programmers use everyday. To most it comes second nature and you may not even have to think about using them. The simplest definition I can think of is: A closure is when you return a function from within a function and the inner function has access to the environment of the outer function(s) OR when you pass in a function as an argument when creating a callback. I hope I helped clarify this for some people. Please leave a comment if you have a suggestion to improve this article. To find more info check out:

No comments:

Post a Comment