Boolean
is a function. Depending on the invocation type, it has different behavior in terms of truthy
and falsy
.
1. Invoking as a simple function
When calling Boolean(value)
as a simple function, it verifies if the argument is a falsy
(false
, null
, undefined
, ''
, 0
,Nan
) or truthy
(all other values: object instances, 1
, true
, etc). This type of invocation returns a boolean primitive type.
It works as expected:
Boolean(null) // prints false
Boolean(0) // prints false
Boolean({}) // prints true
Boolean(-1) // prints true
2. Invoking as a constructor
Like any function in JavaScript, Boolean
can be invoked as a constructor: var b = new Boolean(value)
. This invocation type returns a boolean object instance.
This introduces confusing because JavaScript treats object instances as truthy
value.
var b = new Boolean(null);
!!b // prints true, because b is an object instance
if (b) { // b evaluates to true
//executed code
}
2.1 Why invoking as a constructor is possible
JavaScript allows this constructor invocation to give developer a mechanism to preserve properties creation for a boolean
. A primitive boolean type doesn't save properties assigned to it.
var booleanObject = new Boolean(null);
booleanObject.foo = 'bar'; // create a property
booleanObject.foo // prints 'bar'
var booleanPrimitive = false;
booleanPrimitive.foo = 'bar'; // create a property
booleanPrimitive.foo // prints undefined
2.2 How to make the Boolean object work
Nevertheless, new Boolean(value)
has a mechanism to do comparison. Like any JavaScript object, it has a method valueOf()
, which returns the transformation of the value
to a boolean primitive type (true
for truthy and false
for falsy):
var falsyBoolean = new Boolean(null);
falsyBoolean.valueOf() // prints false, because null is falsy
var truthyBoolean = new Boolean(1);
truthyBoolean.valueOf() // prints true, because 1 is truthy
To make this work in conditionals, it is necessary to avoid any transformations of the boolean object instance into a truthy value. To make this happen, use comparison operator ==
directly:
var falsyBoolean = new Boolean(null);
falsyBoolean == false ? 'falsy' : 'truthy' // prints expected 'falsy'
if (falsyBoolean == false) {
//executed code
}
If an operand in ==
operator is an object and other a primitive type, JavaScript transforms it into a primitive type, which actually consists in calling the valueOf()
method on the boolean object. See more details in this article.
3. How not to get confused
The best rule is to avoid using Boolean
as object instances at all. Boolean(value)
or !!value
is enough to verify the variable truthy state.