Aug 26

Using the || initialization trick

Posted in Javascript      Comments Off on 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; = 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 && || document.body;

it seems good, right? The problem is that elem && will return! 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 ( { = color;

Keep tuned for more on JavaScript.