What is the !! (not not) operator in JavaScript?
I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!
. Can someone please tell me what this operator does?
The context in which I saw this was,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
Coerces oObject
to boolean. If it was falsey (eg 0, null
, undefined
, etc.), it will be false
, otherwise, true
.
!oObject //Inverted boolean
!!oObject //Non inverted boolean so true boolean representation
So !!
is not an operator, it's just the !
operator twice.
Real World Example "Test IE version":
let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false
If you ⇒
console.log(navigator.userAgent.match(/MSIE 8.0/));
// returns null
but if you ⇒
console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// returns true or false
It's a horribly obscure way to do a type conversion.
!
is NOT. So !true
is false
, and !false
is true
. !0
is true
, and !1
is false
.
So you're converting a value to a boolean, then inverting it, then inverting it again.
// Maximum Obscurity:
val.enabled = !!userId;
// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;
// And finally, much easier to understand:
val.enabled = (userId != 0);
!!expr
returns a Boolean value ( true
or false
) depending on the truthiness of the expression. It makes more sense when used on non-boolean types. Consider these examples, especially the 3rd example and onward:
!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!"" === false // empty string is falsy
!!"foo" === true // non-empty string is truthy
!!"false" === true // ...even if it contains a falsy value
!!window.foo === false // undefined is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy; PHP programmers beware!
链接地址: http://www.djcxy.com/p/206.html
上一篇: 运算符重载的基本规则和习惯用法是什么?