For converting non-boolean values to boolean, use Boolean
as a function or use the double NOT operator. Do not use the Boolean()
constructor with new
.
const good = Boolean(expression);
const good2 = !!expression;
const bad = new Boolean(expression); / don't use this!
This is because all objects, including a Boolean
object whose wrapped value is false
, are truthy and evaluate to true
in places such as conditional statements. (See also the boolean coercion section below.)
if (new Boolean(true)) {
console.log("This log is printed.");
}
if (new Boolean(false)) {
console.log("This log is ALSO printed.");
}
const myFalse = new Boolean(false); / myFalse is a Boolean object (not the primitive value false)
const g = Boolean(myFalse); / g is true
const myString = new String("Hello"); / myString is a String object
const s = Boolean(myString); / s is true
Warning:
You should rarely find yourself using Boolean
as a constructor.