Using the || initialization trick

Published Wed, Aug 26 2009 10:55

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.

Filed under:

Comments

# LA.NET [EN] said on Wednesday, September 16, 2009 4:26 PM

JavaScript has three logical operators: &&, || and !. We’ve already seen two posts on the ! and

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover