HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

What does the !! (double exclamation mark) operator do in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
doublemarkthedoesoperatorwhatjavascriptexclamation

Problem

I saw this code:
this.vertical = vertical !== undefined ? !!vertical : this.vertical;


It seems to be using !! as an operator, which I don't recognize. What does it do?

Solution

It converts Object to boolean. If it was falsy (e.g., 0, null, undefined, etc.), it would be false, otherwise, true.

!object  // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation


So !! is not an operator; it's just the ! operator twice.

It is generally simpler to do:

Boolean(object) // Boolean


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

Code Snippets

!object  // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation
Boolean(object) // Boolean
const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // Returns true or false
console.log(navigator.userAgent.match(/MSIE 8.0/));
// Returns either an Array or null
console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// Returns either true or false

Context

Stack Overflow Q#784929, score: 3748

Revisions (0)

No revisions yet.