Boolean Data Type

The Boolean type defines whether something is or is not and can have two literal values true or false. Note that these values are not same as 0 and 1 and that the values are case-sensitive, that is, True and False are not boolean. Boolean values can be set in the following way.


    var isOnline = true; 
    var isOffline = false;

Casting Boolean Values

All data types can be casted to boolean values by using the Boolean() function. For example, the number 0 can be casted to false and any positive numbers are casted to true. Below is a list of different data and how these are casted to boolean

Data TypeTRUEFALSE
Booleantruefalse
NumberAny number not equal to 00 or NaN
StringAny string of length > 0An emptry string
ObjectAny objectnull
Undefinedn/aundefined

It is important to know the boolean casting as this can be used in if-else statements or used in comparisons as shown below.


    var var1 = 0;
    if(var1)
        alert('var1 is true');


    var var2; 
    if(var2)
        alert('var2 has not been initialised');