The Boolean type is the reference type corresponding to the boolean values.
The Boolean type has only two literal values: true and false.
These values are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.
Assignment of Boolean values to variables is as follows:
var found = true; var lost = false;
Boolean literals true and false are case-sensitive, so True and False are valid as identifiers but not as Boolean values.
All Javascript types of values have Boolean equivalents.
To convert a value into its Boolean equivalent, use Boolean() casting function:
var message = "Hello world!"; var messageAsBoolean = Boolean(message);
In the code above, the string message is converted into a Boolean value and stored in messageAsBoolean.
The following table outlines the various data types and their specific conversions.
Data Type | Values Converted To True | Values Converted To False |
---|---|---|
Boolean | true | false |
String | Any nonempty string | "" (empty string) |
Number | Any nonzero number (including infinity) | 0, NaN (See the "NaN" section later in this chapter.) |
Object | Any object | null |
Undefined | n/a | Undefined |
The flow-control statements, such as the if statement, automatically perform this Boolean conversion, as shown here:
var message = "Hello world!"; if (message){ console.log("Value is true"); }
In this example, the alert will be displayed because the string message is automatically converted into its Boolean equivalent (true).
To create a Boolean object, use the Boolean constructor and pass in either true or false:
var booleanObject = new Boolean(true);
Instances of Boolean type override the valueOf() method to return a primitive value of either true or false.
The toString() method is overridden to return a string of "true" or "false" when called.
It is confusing when using Boolean objects in Boolean expressions:
var falseObject = new Boolean(false); var result = falseObject && true; console.log(result); //true var falseValue = false; result = falseValue && true; console.log(result); //false
In this code, a Boolean object is created with a value of false.
That same object is used in AND operator with the primitive value true.
In Boolean math, false AND true is equal to false.
In the code it is the object named falseObject being evaluated, not its value ( false).
All objects are automatically converted to true in Boolean expressions, so falseObject actually is given a value of true in the expression.
Then, true AND true is equal to true.
The typeof operator returns "boolean" for the primitive but "object" for the reference.
A Boolean object is an instance of the Boolean type and will return true when used with the instanceof operator, whereas a primitive value returns false:
console.log(typeof falseObject); //object console.log(typeof falseValue); //boolean console.log(falseObject instanceof Boolean); //true console.log(falseValue instanceof Boolean); //false