The Boolean type has two literal values: true
and false
.
These values are not numeric values.
These values are distinct from numeric values,
so true
is not equal to 1, and false
is not equal to 0.
true
and false
are case-sensitive,
so True and False are valid as identifiers but not as Boolean values.
The following code creates two boolean type variables:
var isOK = true;
console.log(isOK);
var isNotOK = false;
console.log(isNotOK);
The code above generates the following result.
All types of values have Boolean equivalents in Javascript.
To convert a value into its Boolean equivalent, use Boolean() casting function.
The following table lists the outcomes of Boolean()
casting function:
Data Type | True | False |
---|---|---|
Boolean | true | false |
String | nonempty string | empty string("") |
Number | nonzero number and infinity | 0, NaN(NotANumber) |
Object | Any object | null |
undefined | N/A | Undefined |
The following code converts values to Boolean type:
var aString = "Hello world!"; var aBoolean = Boolean(aString); console.log(aBoolean); var anInt = 0; var aBoolean = Boolean(anInt); console.log(aBoolean);
The code above generates the following result.
These conversions are important because flow-control statements, such as the if
statement, automatically perform this Boolean conversion, as shown here:
var message = "hi!";
if (message){
console.log("Value is true");
}
In this example, the console.log is called because the string message is automatically converted
into its Boolean equivalent, which is true
.
The code above generates the following result.