Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to do boolean casting with !! instead of Boolean() in JavaScript?

Tags:

javascript

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?

like image 782
Tower Avatar asked Mar 14 '11 18:03

Tower


3 Answers

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.

like image 127
Andrew Marshall Avatar answered Oct 22 '22 09:10

Andrew Marshall


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.

like image 3
Yahel Avatar answered Oct 22 '22 08:10

Yahel


I can think of 7:

  1. B
  2. o
  3. o
  4. l
  5. e
  6. a
  7. n
like image 2
David Murdoch Avatar answered Oct 22 '22 10:10

David Murdoch