I am aware of Boolean(), String() and Number() casting, and the '' + ...
, !!...
and +...
casting approaches.
I am wondering if there is any reason to not use the function constructors?
In general the use of !!
is often discouraged, as it's not clear to those who haven't seen it before what the actual purpose of it is. That said, it is less than a third the characters of Boolean()
.
Further, I'm not sure how often you actually need to cast to a boolean in Javascript, as it is often implicitly cast since Javascript is weakly typed.
Using the new
operator with those function constructors can have unreliable effects on the typeof
operator. (Edit: As the comments correctly note, this is only when using new Boolean()
instead of Boolean()
)
For example,
var f = new Boolean(true);
if(typeof(f)==="boolean") {//false, since its an object, not boolean
....
}
JavaScript Garden has some great examples.
I can think of 7:
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