The Double NOT (!!) operator magic in JavaScript
JavaScript 0 CommentsYes, it is possible to use a couple of NOT (!
) operators together in JavaScript. JavaScript double not operator returns a Boolean value that depends on the expression’s truthfulness. So, the double not operator !!
is not an operator, it’s just the “Logical NOT ” !
operator twice. And there are no restrictions on using more than twice you can use it 2, 3, 4 as many times as you need.
If we say in short:- JavaScript double not operator converts a non-boolean to an inverted boolean.
The double not operator is a horribly obscure way to do type conversion, but beautifully concise to eyes. So when we actually use it? Okay, I got that I’ll give you a real-world example below.
“Test IE version”:
let isIE8 = false; isIE8 = !! navigator.userAgent.match(/MSIE 8.0/); console.log(isIE8); // returns true or false
If you do console.log(navigator.userAgent.match(/MSIE 8.0/));
it will return either an Array or null.
But if you do console.log(!!navigator.userAgent.match(/MSIE 8.0/));
it will return either true
or false
. Boom you convert it to the boolean
so, you can easily compare it.
Some More Examples
!!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;
A MEME for you

If you liked it Share it.