JavaScript Boolean | JavaScript Tutorials | Learn JS Online
×

JavaScript Boolean

2587

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:


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:


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:


-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



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:



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:



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments