The Linux Page

Returning a Boolean

True or False, the Boolean value which is so often not taken from a variable of type Boolean

Introduction

Today I was thinking about returning a Boolean in my JavaScript function.

I do that all the time in C++ because a function that returns a bool is expected to return true or false.

For example, many people in C++ will do:

bool my_func()
{
  int t = 3;
  ...do some computation against `t`...
  ...now t can be any int number...
  return t;
}

The problem with such code is that the returned value is not a properly formatted boolean value. Compilers do it right, but you could imagine that if you return 0x100 and a bool is saved in a byte.

The correct way to do it in C++ is to explicitly convert `t` to a bool in the return statement as so:

return t != 0;

Now the return value is a bool.

From there I was wondering whether I should do that in other languages too, especially because some languages, such as JavaScript otherwise can leak private data.

JavaScript

If you are writing a library or any kind of low level code, I would suggest that you do take care of such for one good reason, JavaScript will leak private data if you don't.

A statement like the following:

function exists(name)
{
  object = load(name)
  return object
}

does not just return true or false, it returns the whole object.

This may not be a problem in your situation, but if the function is really only expected to return a boolean use the necessary operators to transform your result in a Boolean

The shortest is usually to use the Logical Not as in:

return !!object

If you feel that this is hard to read, another way is to use the ternary operator (?:) as in:

return object ? true : false

If you can, you may also compare the value. For example, if you have a flag which is generally expected to be a boolean but may also be undefined, you could do this to return a valid boolean:

return flag === true

This may look funny, but it's useful to transform the flag variable in a Boolean but keep true if it were true. An interesting aspect of that last one, if the flag variable is anything else than a Boolean, false will be returned. So for example:

return 'string' === true

returns false, when 'string' is considered true. So in:

return 'string' ? true : false

the result is true.