Javascript boolean








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.





Cast to Boolean

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 TypeTrueFalse
Booleantruefalse
Stringnonempty stringempty string("")
Numbernonzero number and infinity0, NaN(NotANumber)
ObjectAny objectnull
undefinedN/AUndefined

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.