Description
The JavaScript Boolean property prototype
allows the addition of new properties and methods to booleans.
The property prototype
is a basic property that is available on all JavaScript objects.
However, it is recommended not to change the prototype
of built-in data types, like Strings, Numbers, Booleans, Arrays, Functions, Objects, Dates, etc.,
Syntax
The property prototype
has the below syntax, where bool
is a boolean value.
Boolean.prototype.name = value;
Parameters
The property constructor
doesn't accept any parameters.
Result
The method constructor
the function that created the Boolean prototype.
Example 1: Adding a New Property
The below example shows how a new property can be added to a JavaScript boolean.
// Add a new property for JavaScript booleans
Boolean.prototype.myColor = "green";
// Create a boolean
var bool = true;
// Call the newly added method that returns the color
document.write(bool); // Prints: true
document.write(bool.myColor); // Prints: green
Output:
true
green
Example 2: Adding a New Method
The below example shows how a new method can be added to a JavaScript boolean.
// Add a new method for JavaScript booleans
Boolean.prototype.myColor = function() {
if (this.valueOf() == true) {
return "green";
} else {
return "red";
}
};
// Create a boolean
var bool = true;
// Call the newly added method that returns the color
document.write(bool); // Prints: true
document.write(bool.myColor()); // Prints: green
Output:
true
green
Browser Support
This property is introduced with ES1 (ECMAScript 1) in 1997.
It is supported in all modern browsers, like Google Chrome, Internet Explorer or Edge, Firefox, Apple Safari, Opera, etc.,