Detecting Booleans

Booleans are thankfully very simple to check. The typeof operator correctly evaluates to "boolean" for values of true and false:

typeof true;  // => "boolean"
typeof false; // => "boolean"

It's rare that we'll want to do this, though. Usually, when you are receiving a Boolean value, you are most interested in checking its truthiness rather than its type.

When placing a Boolean value in a Boolean context, such as a conditional statement, we are implicitly relying on its truthiness or falsiness. For example, take the following check:

function process(isEnabled) {
if (isEnabled) {
// ... do things
}
}

This check does not determine whether the isEnabled value is truly Boolean. It just checks that it evaluates to something truthy. What are all the possible values that isEnabled could be? Is there a list of all these truthy values? These values are virtually infinite, so there is no list. All we can say about truthy values is that they are not falsy. And as we know, there are only seven falsy values. If we wish to observe the truthiness or falsiness of specific values, we can always cast to a Boolean via the Boolean constructor invoked as a function:

Boolean(true); // => true
Boolean(1); // => true
Boolean(42); // => true
Boolean([]); // => true
Boolean('False'); // => true
Boolean(0.0001); // => true

In most situations, the implicit coercion to a Boolean is sufficient and won't end up biting us, but if we ever wish to absolutely determine that a value is both Boolean and specifically true or false, we can use the strict equality operator to compare them, like so:

if (isEnabled === true) {...}
if (isEnabled === false) {...}

Due to the dynamic nature of JavaScript, some people prefer this level of certainty but usually, it isn't necessary. If the value we are checking is obviously intended as a Boolean value, then we can use it as so. Checking for its type via typeof or strict equality is usually unnecessary unless there is a possibility that the value may be non-Boolean.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.27.244