JavaScript Boolean

by Monika Dadool 23-Jun-19

0 279


Sometimes there occurs a condition, where there is a need of a data type that contains only two values such as yes/no, on/off or true/false. In such condition, Boolean data type can be used in JavaScript, which permits only two values like true or false.

# Boolean values are used when comparison and conditions are performed on JavaScript.
# Everything with a real value is treated true with Boolean datatype in JavaScript.
# Boolean function can be used to find out whether an expression is true.

A program illustrating Boolean function

<html>
<body>
<p>display the value of boolean(27>4):</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var a="27>4";
document.getElementById("demo").innerHTML=Boolean(a);
}
</script>
</body>
</html>

Output:

JavaScript Boolean


Second Program:

<html>
<body>
<p>display the value of boolean(4>27):</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var a=4>27;
document.getElementById("demo").innerHTML=Boolean(a);
}
</script>
</body>
</html>

Output:

JavaScript Boolean


Some important notes related to Boolean data type in JavaScript
New keyword is used to create Boolean objects e.g. var wrong=new Boolean(false);
An empty string,0, NAN and null are treated as false in JavaScript.

Example:
<html>
<body>
<p>display the value of an empty string:</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var g="";
document.getElementById("demo").innerHTML=Boolean(g);
}
</script>
</body>
</html>

Output:

JavaScript Boolean


-o value

<html>
<body>
<p>display the value of -0 :</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var g=-0;
document.getElementById("demo").innerHTML=Boolean(g);
}
</script>
</body>
</html>

Output:
valuev

JavaScript Boolean


The Boolean Value of 0 in alway false in JavaScript:
<html>
<body>
<p>display the value of 0 :</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var g=0;
document.getElementById("demo").innerHTML=Boolean(g);
}
</script>
</body>
</html>

Output:

JavaScript Boolean


The value of undefined value

<html>
<body>
<p>display the value of undefined boolean :</p>
<button onclick ="mybooleanfun()">click me</button>
<p id="demo"></p>
<script>
function mybooleanfun(){
var g;
document.getElementById("demo").innerHTML=Boolean(g);
}
</script>
</body>
</html>

Output:
JavaScript Boolean


Share:


Comments

    Waiting for your comments

Leave a Reply