Javascript - Data Types Boolean

Introduction

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).