Boolean() casting function

Boolean() casting function converts a value into its boolean equivalent. 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 a nonempty string to Boolean type:

 
<!DOCTYPE html>
<html>
<head>
    <title>Boolean Example</title>
    <script type="text/javascript">
          
        var aString = "Hello world!";
        var aBoolean = Boolean(aString);
        
        document.writeln(aBoolean); //true
    </script>
</head>
<body>
  
</body>
</html>
  
Click to view the demo

The following code converts a zero value to Boolean type:

 
<!DOCTYPE html>
<html>
<head>
    <title>Boolean Example</title>
    <script type="text/javascript">
          
        var anInt = 0;
        var aBoolean = Boolean(anInt);
        
        document.writeln(aBoolean); //false
 
              
    </script>

</head>
<body>
  
</body>
</html>
  
Click to view the demo

Some statment, such as the if statement, automatically perform this Boolean conversion:

 
<!DOCTYPE html>
<html>
<head>
    <title>Boolean Example</title>
    <script type="text/javascript">
          
        var aString = "Hello world!"; 
        
        if (aString){ 
           document.writeln("value is true"); 
        }

        aString = "";
        if (aString){ 
           document.writeln("value is true"); 
        }else{
           document.writeln("value is false"); 
        }
 
        aString = null;
        if (aString){ 
           document.writeln("value is true"); 
        }else{
           document.writeln("value is false"); 
        }
   
              
    </script>

</head>
<body>
  
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Data Types:
  1. JavaScript Data Types
  2. typeof Operator
  3. The Undefined Type
  4. null Type
  5. null vs undefined
  6. Boolean Type
  7. Boolean() casting function
  8. The Literials of Number Type
  9. Octal Integer
  10. Hexadecimal
  11. Floating-Point Values
  12. Value range
  13. NaN
  14. Number Conversions:Number(), parseInt() and parseFloat()
  15. Number() function
  16. parseInt()
  17. parseFloat()
  18. The String Type
  19. String Literals and Escapes
  20. Get the String Length
  21. Converting to a String with toString() method
  22. Convert Number to String with radix
  23. Convert to String with String() casting function