Asked : Nov 17
Viewed : 22 times
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;
Nov 17
Converts Object
to boolean
. If it was false (e.g. 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":
const 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 either an Array or null
But if you ⇒
console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// returns either true or false
answered Jan 13
The double negation(!! ) operator is the! Operator twice and calculates the truth value of a value. It returns a Boolean value, which depends on the truthiness of the expression., Is the !! (not not) operator in JavaScript equivalent to reverse process of not-operator?, What is the use of EXIST and EXIST NOT operator with MySQL subqueries?, Double not (!!) operator in PHP
Consider (!!p) as !(!p), here’s an example:
If p is a false value, !p is true, and!!p is false.
If p is a true value, !p is false, and!!p is true.
Here’s another example:
0 === false is false.!!0 === false is true.!!0 === false!!parseInt("foo") === false!!1 === true!!-1 === true!!false === false!!true === true
answered Jan 13
Use logical not operator two times
it means !true = false
and !!true = true
answered Jan 13
The dilemma of "Should I use ==
or ===
in JavaScript comparison" is equal or analogous to a question of: "Should I use a 'spoon' or a 'fork' for eating.
The only reasonable answer to this question is that
==
for loose Type comparisons.===
for strong Type comparisons.That's because they are not the same. They don't have the same purpose and are not meant to be used for the same purpose.
Of course, both 'forks' and 'spoons' are meant for 'eating', but you will choose to use them accordingly to what you've been served to eat.
Meaning: you'll resolve to use a 'spoon' i.e.: ==
for having a 'soup', and/or the 'fork' i.e.: ===
for picking.
Asking if it is better to use a "fork" or a "spoon" for "eating" - is equal to asking if it is better to use a static [===] versus dynamic [==] eq., op. in JS. Both questions are equally wrong and reflect a very narrow or shallow understanding of the subject in question.
answered Jan 13