25 Feb JavaScript Booleans
A Boolean object in JavaScript has two values true and false. Let us see how to create a Boolean and Boolean object. We will also see the Boolean properties and methods with live running examples.
Create a Boolean and Boolean object
Let us see how to create a Boolean:
1 2 3 |
let b = true; |
We can create a Boolean object using the new keyword:
1 2 3 |
let b = new Boolean(true); |
JavaScript Boolean Properties
We have a constructor property in the Boolean object. Let us understand the property with an example.
boolean.constructor
Using the constructor property, a reference to the Boolean function is returned. This function created the object. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Boolean</h1> <p id="test"></p> <script> var b = new Boolean( ); document.getElementById("test").innerHTML = b.constructor </script> </body> </html> |
Output
JavaScript Boolean Methods
We have built-in methods for the Boolean object. Let us understand some of the methods with examples:
- toString()
- valueOf()
JavaScript toString() method
Use the toString() method to return the string representation based on the value of the object. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Boolean</h1> <p id="test"></p> <script> // Boolean object var b = new Boolean(true); // Return the string representation document.getElementById("test").innerHTML = b.toString() </script> </body> </html> |
Output
JavaScript valueOf() method
Use the valueOf() method in JavaScript to return the Boolean object. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <h1>JavaScript Boolean</h1> <p id="test"></p> <script> // Boolean object var b = new Boolean(false); // Return the value of the Boolean object document.getElementById("test").innerHTML = b.valueOf() </script> </body> </html> |
Output
No Comments