Using the || initialization trick

Suppose you’ve got a function and you expect it to receive some optional parameters. In these cases, you’d like those optional parameters to be initialized with a predefined value. Can we do that in Javascript? Yes, we can and all we need is to use the || operator. The following snippet should make this point clear:

function changeTextColor(color, elem) {
    elem = elem || document.body;
    elem.style.color = color;
}

As you can see, we expect two parameters. The initial check tries to ensure that elem points to a valid HTML element. It’s that simple and there really isn’t much more to say about it. Keep in mind that you shouldn’t get too fancy with this kind of tricks. For instance, I recall that a a colleague of mine which was getting started with JavaScript tried to be  a little too smart and wrote the following code:

elem = ( elem && elem.style) || document.body;

it seems good, right? The problem is that elem && elem.style will return elem.style! Was he right in performing the check? Yes, he was, but he did it in the wrong place. If you want to be that clever, then you’d better understand how && and || work. Btw, here’s a revised version of the previous method which checks for the style object before setting its color property:

function changeTextColor(color, elem) {
    elem = elem || document.body;
    if (elem.style) {
        elem.style.color = color;
    }
}

Keep tuned for more on JavaScript.

Advertisements

~ by Luis Abreu on August 26, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: