Member Sign In
Not a member?

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.

Sign in with OpenID
Sign In
Webmonkey is a property of Wired Digital.
processing...
Join Webmonkey

Please send me occasional e-mail updates about new features and special offers from Wired/Webmonkey.
Yes No

Please send occasional e-mail offers from Wired/Webmonkey affiliated web sites and publications, and carefully selected companies.
Yes No

I understand and agree that registration on or use of this site constitutes agreement to Webmonkey's User Agreement and Privacy Policy.
Webmonkey is a property of Wired Digital.
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.

or
Webmonkey is a property of Wired Digital.
processing...

Welcome to Webmonkey

A private profile page has been created for you.
As a member of Webmonkey, you can now:
  • edit articles
  • add to the code library
  • design and write a tutorial
  • comment on any Webmonkey article
Close
Webmonkey is a property of Wired Digital.

Sign In Information Sent

An e-mail has been sent to the e-mail address registered in this account.
If you cannot find it in your in-box, please check your bulk or junk folders.
Sign In
Webmonkey is a property of Wired Digital.

Free Yourself from Conditions in JavaScript

/skill level/
/viewed/
0 Times

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.
Edit this article
Reddit Digg
 
Subscribe now

Special Offer For Webmonkey Users

WIRED magazine:
The first word on how technology is changing our world.

Subscribe for just $10 a year