Given that in JavaScript
console.log("var F=new Boolean(false)")
console.log("( F != (F==false))",(( F != (F==false)) ? "TRUE" : "false"));
console.log("(!F != (F==false))",((!F != (F==false)) ? "TRUE" : "false"));
prints:
( F != (F==false)) TRUE
(!F != (F==false)) TRUE
which means that Boolean objects are not dop-in substitutes for a boolean primitive in typical conditions like:
if(someBoolean) ... // always true
if(!someBoolean) ... // always false
And that JavaScript's Set
and Map
collections permit any type, including primitives.
What use are Boolean objects, in particular; and the objects representing other primitive types in general, since they have all sort of weird in consistencies associated with them?
Note: I am specifically asking what are the use-cases (if any), not how they are different from their primitive counterparts.
A JavaScript Boolean represents one of two values: true or false.
Boolean Operators are simple words (AND, OR, NOT or AND NOT) used as conjunctions to combine or exclude keywords in a search, resulting in more focused and productive results. This should save time and effort by eliminating inappropriate hits that must be scanned before discarding.
It is recommended that you use the Boolean() function to convert a value of a different type to a Boolean type, but you should never use the Boolean as a wrapper object of a primitive boolean value.
A Boolean variable has only two possible values: true or false. It is common to use Booleans with control statements to determine the flow of a program. In this example, when the boolean value "x" is true, vertical black lines are drawn and when the boolean value "x" is false, horizontal gray lines are drawn.
Boolean objects are just objects, and thus are truthy.
console.log(!!new Boolean(true)); // true
console.log(!!new Boolean(false)); // true
Boolean objects exist because this way you can add methods to Boolean.prototype
and use them on primitive booleans (which will be wrapped into booolean objects under the hood).
Boolean.prototype.foo = function() {
console.log("I'm the boolean " + this + "!!");
};
true.foo();
false.foo();
They are also useful when you want to store properties in a boolean.
var wrappedBool = new Boolean(false);
wrappedBool.foo = "bar";
console.log("Property foo: ", wrappedBool.foo); // "bar"
console.log("Unwrapped bool: ", wrappedBool.valueOf()); // false
But that's not recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With