javascript tutorial - [Solved-5 Solutions] What is the !!(not not) operator in javascript ?
- javascript - java script - javascript array
Problem:
We saw some code that seems to use an operator We 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 We saw this was,
Solution 1:
Coerces oObject to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true.
So !! is not an operator, it's just the ! operator twice.
Real World Example "Test IE version":
If we =>
but if we =>
Solution 2:
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.
Solution 3:
!!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:
Solution 4:
!!foo applies the unary not operator twice and is used to cast to boolean type similar to the use of unary plus +foo to cast to number and concatenating an empty string ''+foo to cast to string.
Instead of these hacks, we can also use the constructor functions corresponding to the primitive types (without using new) to explicitly cast values, ie
Solution 5:
It's just the logical NOT operator, twice - it's used to convert something to boolean, e.g.: