A closure, in JavaScript, can simply be described as a retained scope; at least, this is how I think of it. The benefit of a closure is in the fact that it retains the scope (the “scope chain”) of the outer (or “parent”) execution context. This behaviour can be used in a number of different ways and has become a useful remedy for quite a few JavaScript gotchas; one of the most common being the “looping problem”.
The looping problem occurs when you create a function within a loop and expect the current value of a variable to retain itself within that new function even though it changes in the loops context before your new function is called. Here’s en example:
var myElements = [ /* DOM Collection */ ];
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
alert( 'You clicked on: ' + i );
};
}
By the time myElements[0].onclick is triggered the value of i will be 99, meaning that whatever element you click on you’ll always get the message, “You clicked on: 99″.
This problem can be solved by creating a function and calling it on each iteration of the loop, while passing i; calling the function will form a brand new execution context where the value of i is retained and can be used in any way within that context, including within the returned function.
function getHandler(n) {
return function() {
alert( 'You clicked on: ' + n );
};
}
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = getHandler(i);
}
Now it works perfectly! A common shortcut used is to create and call the function at the same time, using what is known as a "self invoking anonymous function":
This is the first post of a hopeful series dubbed “JavaScript, tip of the week“; I will try to release a tip in some form every week.
I’m young and haven’t been doing this programming thing for very long so the fact that I’ve never had to use a switch-case statement (to my recollection) might not be very impressive; actually you probably see this as a bad thing and you might even be wondering why I haven’t. I can’t really explain why but I seem to have an inherent dislike of things like this:
switch (something) {
case 1:
doX();
break;
case 2:
doY();
break;
case 3:
doN();
break;
// And so on...
}
The fictional author of this code obviously doesn’t know enough about JavaScript to make use of its various other constructs, most of them ten times more suited to this situation than an ugly switch statement. It’s not its appearance that truly annoys me though; it’s the knowledge that there are so many easier and more graceful ways of achieving such functionality.
Switch statements are considered as useful when you have a single variable and dependent on its value you want to carry out one of a number of different tasks. Using multiple if-else clauses doesn’t seem appropriate so the switch statement is often called upon to lend a hand. I’m sure most of you are familier with it and have seen it more than once before.
Let’s take the example from above; dependent on the value of something we run doX, doY or doN. In JavaScript, the same logic can be expressed with a simple lookup table in the form of an object:
var cases = {
1: doX,
2: doY,
3: doN
};
if (cases[something]) {
cases[something]();
}
Not only is this cleaner but it’s also reusable, modifiable and accessible… All the conditions are saved as part of an object, so if you ever need to recall or change those conditions then it’s as easy as cases[condition].
I suspect this covers about 90% of situations where a switch-statement is used; the remaining 10% are probably legitimate uses. Using a lookup table as an alternative to the Switch statement is not new; in fact this is the only way such logic can be expressed in both the Python and Lua languages, both of which have no support for switch statements.
So, my message is the following: do not use switch-case constructs unless absolutely necessary. Why? – Because there are better alternatives; simple as that!
Read more about the “Switch Statement” here: en.wikipedia.org/wiki/Switch_statement.