Boolean

The Boolean primitive type in JavaScript is used to represent either true or false. These polar opposites are its only values:

const isTrue = true;
const isFalse = false;

Semantically, Booleans are used to represent real-life or problem domain values that can be considered on or off (0 or 1), for example, whether a feature is enabled, or whether the user is over a certain age. These are Boolean characteristics and so are appropriate to express via Boolean values. We can use such values to dictate control flow within a program:

const age = 100;
const hasLivedTo100 = age >= 100;

if (hasLivedTo100) {
console.log('Congratulations on living to 100!');
}

The Boolean primitive, just like String and Number, can be manually wrapped in a wrapper instance like so:

const isTrueObj = new Boolean(true);

Note that, once you do this, Boolean will behave just like any other object in conditional statements. So, the following conditional statement will succeed, even though the wrapped primitive value is false

const isFalseObj = new Boolean(false);

if (isFalseObj) {
// This will run
}

The Boolean instance here is not equivalent to its primitive value; it merely contains its primitive value. isFalseObj will behave just like any other Object in a Boolean context, resolving to trueManually wrapping a Boolean like this is not especially useful and should be avoided as an anti-pattern in most programs as it doesn't behave according to Boolean semantics and may produce unexpected results.

Boolean primitives are returned by JavaScript's logical operators such as greater than or equal to (>=) or strict equality (===). We'll cover these in more detail in Chapter 8, Operators.

 

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

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