JavaScript's Boolean function?

Front End TechnologyJavascriptObject Oriented Programming

Boolean function

While developing, a developer may come across yes/no situation. At that point of time Boolean() function can be used. It results only in true or false. Let's discuss it in detail.

syntax

Boolean(exp);

It takes an expression and scrutinizes it and displays either true or false based on the validity of the expression.

Example-1

In the following example, various values have been checked whether they are true or not using Boolean() function. If any value has any legitimate value then it results in true else it results in false. 

<html>
<body>
<p id = "boolean"></p>
<script>
   var a = 0;                         
   document.write(Boolean(a));          ///  displays false
   var b = 1;
   document.write(Boolean(b));          /// displays true      
   var x = Boolean(100);
   var y = Boolean("Hello");
   var z = Boolean('false');
   document.getElementById("boolean").innerHTML =
   "45 is " + x + "</br>" +
   "a string 'Hello' is " + y + "</br>" +
   "a false value is " + z ;
</script>
</body>
</html>

Output

45 is true
a string 'Hello' is true
a false value is true

false
true


Example-2

In the following example, an expression is sent inside the Boolean() function to check the expression's validity. If the expression is legitimate then true will be displayed as output else false is displayed as output.

<html>
<body>
<script>
   document.write(Boolean(10 > 5));
   document.write("</br>");
   document.write(Boolean(1 > 4));
</script>
</body>
</html>

Output

true
false
raja
Published on 23-Aug-2019 18:47:10
Advertisements