Computers & ProgrammingFrontend DevelopmentJavaScript

JavaScript Boolean Object

In JavaScript, the Boolean object is a wrapper for the Boolean data type. The Boolean object is commonly used to convert a non-Boolean value to a Boolean value. The Boolean object represents two values, either true or false. The following example creates a Boolean object.

var myB = new Boolean();    

If the Boolean object has no initial value, or if the passed value is one of the following values, the Boolean object returns false. Any other value passed to the Boolean Object will return true.

  • 0
  • -0
  • null
  • ""
  • false
  • undefined
  • NaN

Here are some examples of how to use the Boolean object. You can copy and paste this code into the HTML editor to try it yourself.

<html>
<body>

<script type="text/javascript">
    var myB1 = new Boolean(0);
    var myB2 = new Boolean(1);
    var myB3 = new Boolean("");
    var myB4 = new Boolean(null);
    var myB5 = new Boolean(NaN);
    var myB6 = new Boolean(false);
    var myB7 = new Boolean("false");

    document.write("0 is boolean " + myB1 + "<br />");
    document.write("1 is boolean " + myB2 + "<br />");
    document.write("An empty string is boolean " + myB3 + "<br />");
    document.write("null is boolean " + myB4 + "<br />");
    document.write("NaN is boolean " + myB5 + "<br />");
    document.write("false is boolean " + myB6 + "<br />");
    document.write("The string \"false\" is boolean " + myB7 + "<br />");
</script>

</body>
</html>

Always keep in mind that JavaScript is case-sensitive.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top