开发者

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

I am aware of Boolean(), String() and Number() casting, and the '' + ..., !!... and +... casting approaches.

I am wondering if there is an开发者_如何学JAVAy 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:

  1. B
  2. o
  3. o
  4. l
  5. e
  6. a
  7. n


This shouldn't be an issue, but someone could replace the Boolean function with their own making the two ways not equivalent. For example:

Boolean = function(x) {
    alert('Evil');
    return !x; // Oops
}

var x = 0;
console.log(!!x); // false
console.log(Boolean(x)); // true

That's mostly a theoretical difference, since you shouldn't be replacing built in constructors, but it is a difference.

There could also be a small performance difference because of the name lookup and function call overhead. I wouldn't worry about either of those though in most cases. Just use whichever version you prefer.


It might just be a case of using less characters, making for a more compact script.


I find using new with these types can lead to easy confusion or tricky bugs:

var x = new Boolean(true);
console.log( x ); // true
console.log( typeof x ); // "object"

var y = new Boolean('false');
console.log( y ); // true
console.log( typeof y ); // "object"

var z = false;
console.log( z ); // false
console.log( typeof z ); // "boolean"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜