Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What practical use is a Boolean object in Javascript?

Tags:

javascript

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.

like image 927
Lawrence Dol Avatar asked Dec 06 '16 19:12

Lawrence Dol


People also ask

What is meant by Boolean in JavaScript?

A JavaScript Boolean represents one of two values: true or false.

What is the point of booleans?

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.

Should I use Boolean in JS?

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.

How do you use booleans?

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.


1 Answers

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.

like image 164
Oriol Avatar answered Sep 21 '22 12:09

Oriol