chenb•log

I don’t mind if I’m incomprehensible

Archive for March 2010

JavaScript Closures (a fairly simple explanation of)

with 3 comments

I had a job interview recently.  I started the day by missing a flight, and then it was mostly downhill from there.  However, I did pretty much nailed a JavaScript question where the solution involved using closures.  The interviewer sounded surprised that I gave the solution; I was surprised at his reaction because I thought higher order programming, anonymous functions, and closures are common knowledge in JavaScript programming.

Below is my attempt at an explanation of what was used in the solution.  Hopefully it will help someone in an interview.

In JavaScript, you could define an anonymous function and immediately execute it:

(function(){ alert('zombies!'); }())

The wrapping parentheses are necessary here to turn that piece of code into an expression.  Otherwise you’d have a function declaration without a function name, and the JavaScript console will say something about a syntax error.  Alternatively, you could also write

(function(){ alert('zombies!'); })()

or

var testo = function(){ alert('zombies!'); }();

In the last example, we could leave out the parentheses because the code is in an assignment expression.

Of course, a function can accept arguments, so now let us do

(function(thing){ alert(thing); })('zombies!');

Same thing, but more work.

JavaScript functions can also create and return functions.  That means we can rock

(function(thing){ return function(){alert(thing);} })('zombies!')();

That’s even more work, with more parentheses.  In the above example, we create a function and called it with the string ‘zombie!’ as the argument.  That (outer) function then creates a function and return it, then we immediately call it with that last pair of parentheses.

To make it (slightly) more readable

var testo = function(thing){ return function(){alert(thing);} })('zombies!');
testo();

testo is the function returned by the outer function. And it always alerts about zombies. That’s the closure bit. The string “zombies!” has been closed over in the returned function.

One instance where this is useful is when you need the value of a variable that’s being updated, let’s say, in a loop. For example

var things = ['ghosts!', 'ghouls!', 'vampires!', 'zombies!'];
var alerts = {};
for (var i in things) {
    alerts[things[i]] = function(thing) { return function(){ alert(thing); }; }(things[i]);

}

There we go, closures.

Advertisements

Written by Barry

March 13, 2010 at 4:52 pm

Posted in Nerdy

Tagged with ,