A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.
It's fast and free.
processing...Retrieve Sign In
Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.
processing...Welcome to Webmonkey
- edit articles
- add to the code library
- design and write a tutorial
- comment on any Webmonkey article
Sign In Information Sent
Free Yourself from Conditions in JavaScript
/skill level/
/viewed/
Introduction
Now I love an if() or a switch() as much as the next monkey, but in these days where we push JavaScript (and browsers) to their limits in the name of Web 2.0 perhaps there's a better way to handle complex conditions. Maintaining big if() and switch() trees can be tricky and time consuming, and heaven help you if you need to hand it off to someone else not as familiar with your code. One also has to keep in mind that conditional evaluations take time, and processor horsepower, and that that time adds up if you have a lot of code executing client-side.
This tutorial will show you how to harness the power of function pointers and arrays in JavaScript to make conditional statements faster and easier to maintain.
What you'll need
text editor and a browser
Steps
Let's take the classic code test that everyone is given when interviewing: write some code that handles an incoming variable. If that variable's value is "red," alert "Ruby Slippers" and if the value is "blue," alert "Ice Cubes."
The typical solution would be:
function doColorDetect(s_val_fp) {
switch(s_val_fp) {
case 'red':
alert('Ruby Slippers');
break;
case 'blue':
alert('Ice Cubes');
break;
}
}
But there's a whole other way to deal with this problem using arrays and function pointers. Function pointers, for the uninitiated, are a powerful and underused aspect of JavaScript. They work like this...
function doSomething() { //referenced function
alert('foo');
}
var f_pointer = doSomething; //assign the function to another variable
f_pointer(); //alert "foo"
In the above example, we created a function called doSomething();. Then we created a variable called f_pointer and assigned it the value of doSomething. Notice that the line wasn't var f_pointer = doSomething();. By omitting the () after the function name, it is assigned as a reference and not executed. This finally allows us to invoke the variable f_pointer(); with the parentheses after it, causing it to execute the function it references.
And now a note about arrays in JavaScript. As we know, arrays can have numerical keys (e.g. a_foo[0], a_foo[1], etc.). JavaScript, like PHP, will also allow for named keys (e.g. a_foo['one'], a_foo['two'], etc.).
Now let's refactor our earlier solution to something a little more exotic.
function doColorDetect(s_val_fp) {
a_function = new Array();
a_function['blue'] = doBlue;
a_function['red'] = doRed;
a_function[s_val_fp]();
}
function doBlue() {
alert('Ice Cubes');
}
function doRed() {
alert('Ruby Slippers');
}
The above example will perform as the original did by assigning the individual handling functions to named keys in the array a_function. When the value is passed in the line a_function[s_val_fp](); it then executes the referenced function based on the value of the string acting as a named key in the array.
No, this is not a solution for all purposes and will not replace conditional statements where you need to evaluate a range of values as you wouldn't want to write an array with all possible permutations. It WILL get you over a boolean true/false hump if you can be clever with type casting. Just take your boolean, say b_val = true; and cast it to a number i_val = Number(b_val) and you can catch the 1/0 in array indices.
- This page was last modified 22:40, 28 November 2008.
/related_articles/
Special Offer For Webmonkey Users
WIRED magazine:
The first word on how technology is changing our world.
