Short-circuit evaluation in JavaScript (part 2)

Andrey Zakharov
03-04-2018

The fist part of post is here: Short-circuit evaluation in JS (part 1)

In the first part you learned what is short-circuit evaluation in JS and how to use this as a trick for some useful construction in your javascript application. Now we know how to make a chain of steps using boolean AND operator. But this is not the end, right? We have OR operator also, maybe we can use it for something too? And the answer is YES.

To evaluate OR not to evaluate

So, once again about short-circuit. When we have a chain of AND operators, we know that when we meet false, we can stop and return it immediately. It also prevents us from touching any further elements in a chain, which is very convenient when we have several functions which should be performed as a union action without any fails. Now, about OR operators. In contrary, here we’re waiting for the first true value in a chain, because any true value will make the result of evaluation true with no doubt.

But wait, speaking that value will be true is not totally correct. As we know, js has a very flexible type system, so we can pass variables with any type into boolean expression. During evaluation, each value will be converted to boolean, but the resultive value will be returned as is, without conversion.

var result = false || null || 'string value' || 'another string';

console.log(result);

Wow, that’s something. Now result variable is assigned to ‘string value’. Due to short-circuit, it didn’t touch ‘another string’. So, in other words, as a result we have the first value which returns true in boolean conversion. It’s easy to check what would be the boolean value of your variable, just adding two exclamations before. One exclamation is NOT operator, so it will convert our variable into boolean type but with inversion, then we apply second NOT to make it straight.

Some common values which better to check and learn by heart is:

  1. Undefined variable
  2. Null
  3. 0 (number zero)
  4. ” (empty string)

Show me the trick

Since we’re using javascript in frontend applications usually, we often deal with rendering some values on a screen (not put it directly to html, I hope, but just retrieve something from data source and pass it further to template). So, that’s also a very common situation when some values are empty or undefined and our page contains literally nothing. Check the example:

var user = {
    name: 'Andrey',
    email: 'andrey@competa.com',
    phone: '',
}

console.log('The phone number of user is ', user.phone);

Probably, the registration form did not require to fill phone number, so Andrey left it empty. But the administrator and other users are very curious of this information still. Well, they don’t know what’s wrong, they just see The phone number of user is . Empty space. Voidness. Not so user-friendly.

Make it user-friendly

var userPhone = user.phone || 'not defined';

console.log('The phone number of user is ', userPhone);

Alright! In case user phone contains any not good value, we will show fallback value instead. This is useful not only to fill placeholders with default values on a page. For instance, application can operate with some settings, but also keeps a default configuration:

function init(userConfig) {

    var defaultConfig = {

        //default values

    }

    var configToInit = userConfig || defaultConfig;

    doSomethingWith(configToInit);

}

init();

Cool! Even we don’t pass anything to init() function, we’re still safe, init function has default config values to use. Of course, we can use a chain of fallback values without limits. For instance, we may have several non-trusted sources: user input, local storage, backend response. So we can compose a chain of OR operators to safely reach our local default value.

Troubleshooting

Do you remember I showed you some special values that has a specific result after conversion into boolean type? When we deal with undefined, null or empty string and use our fancy fallback operator, we may expect to have a default value as a result. But what about numbers? 0 (zero) is defined enough, but it will return false as boolean. It means, that result will be unexpectable:

var counter = 0,
    count = counter || 'unknown number of';

console.log(count, 'users on a site');

We expect to see a message “0 users on a site”, but we’ll see “unknown number of users on a site”. So, to deal with it, we can convert a number to string before displaying it in UI. Anyway, take care of such cases when you’re going to use boolean conversion. Happy coding!

LEAVE A REPLY

you might also like