JavaScript | Boolean.prototype with Examples

The Boolean.prototype is an inbuilt property in JavaScript which is used to add a new property to the all Boolean instances. There is constructor prototype which is used to add properties or methods to all Boolean objects.
Syntax:

Boolean.prototype.name = value

Here “name” specifies the property or method name to be used and “value” specifies the value used by the function.
Some methods related to Boolean.prototype property :

  • Boolean.prototype.valueOf() : It simply returns the value of boolean object.
  • Boolean.prototype.toString() : This method returns a string according to the Boolean value.

JavaScript code to show the working of this property:
Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

function check(v1) {
    if (v1 == true)
        return (v1 + " is True.");
    else
        return (v1 + " is False.");
}
 
//adding a new property
Boolean.prototype.myVar = false;
 
//adding a new method
Boolean.prototype.myMethod = check;
 
//creating a new boolean object
var Obj1 = new Boolean();
 
document.write(Obj1.myMethod(1) + "<br>");
document.write(Obj1.myMethod(0) + "<br>");
document.write("myVar = " + Obj1.myVar);

chevron_right


Output:

1 is True.
0 is False.
myVar = false

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

Boolean.prototype.CheckGeek = function(pro) {
    if (pro == true) {
        return "Pro Geek";
    } else {
        return "Geek";
    }
};
 
//creating a new boolean object
var Obj = new Boolean(true);
 
document.write("Obj.CheckGeek(true) = " + Obj.CheckGeek(true) + "<br>");
document.write("Obj.CheckGeek(false) = " + Obj.CheckGeek(false) + "<br>");
document.write("Obj.valueOf() = " + Obj.valueOf() + "<br>");
document.write("Obj.toString() = " + Obj.toString());
 
 
 
 
         

chevron_right


Output:

Obj.CheckGeek(true) = Pro Geek
Obj.CheckGeek(false) = Geek
Obj.valueOf() = true
Obj.toString() = true

See also:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.