JavaScript Double Exclamation Mark Comprehensive Guide

The double exclamation mark (!!) in JavaScript is an interesting and useful operator. Despite its cryptic appearance, the double exclamation mark actually serves an important purpose in JavaScript programs. In this comprehensive guide, we’ll cover everything you need to know about using, understanding, and leveraging JavaScript’s double exclamation marks.

An Overview of Double Exclamation Marks

The !! operator in JavaScript is referred to as the double NOT operator. It is composed of two exclamation marks (NOT operators) together.

On a basic level, the !! operator is used to convert a value to a Boolean true or false. Any value passed to !! will be coerced into a Boolean:

!!0 // false
!!1 // true
!!'hello' // true
!!null // false
!![] // true
!!{} // true
JavaScript

So why might this be useful? The double NOT can come in handy for converting any value to a definitive true or false Boolean. This allows you to simplify conditional checks and comparisons in code.

Additionally, the !! operator is often used for empty checks. Since empty values like 0, null, undefined, and empty strings and objects evaluate to false when passed to !!, you can check if a value is “empty” like this:

const value = ''
if (!!value) {
  // this code will not run
} 
JavaScript

These examples demonstrate the core ideas behind the !! operator. But there’s much more to cover about how, when, and why to use !! in JavaScript.

Converting to Boolean

As we saw above, one of the main uses of !! is to convert a value to its Boolean equivalent.

In JavaScript, every value has an inherent Boolean value already:

  • Numbers evaluate to true, except for 0 which is false
  • Strings evaluate to true, except for empty string ” which is false
  • Arrays evaluate to true, except for empty arrays [] which are false
  • Objects evaluate to true, except for null which is false
  • undefined evaluates to false

And so on. But you don’t always want to rely on JavaScript’s own type coercion rules for Boolean evaluation.

The !! operator gives us a simple way to force any value down to a Boolean true or false.

This can be useful for simplifying conditionals:

function printIfPositive(num) {
  // without !!
  if (num > 0) {
    console.log(num)
  }

  // with !!
  if (!!num > 0) {
   console.log(num)
  }
}
JavaScript

Or for writing expressions:

const isAdmin = user.permissions.includes('ADMIN') || !!user.isOverride;
JavaScript

In general, if you ever need to force a value into a true or false, !! is a good choice over more complex expressions.

Empty Checks

Another common use of !! is to check if a value is “empty” or has no contents.

As we saw earlier, many empty values in JavaScript evaluate to false when passed to !!:

!!0 // false
!!'' // false  
!!null // false
!!undefined // false
!![] // false
!!{} // false
JavaScript

This provides a shortcut for checking emptiness:

function doIfHasContent(value) {
  if (!!value) {
    // do something
  }
}
JavaScript

Or with objects:

if (!!obj.property) {
  // obj has property
}
JavaScript

You will often see !! used with empty checks for strings, arrays, and objects.

However, one gotcha is that empty objects and arrays will still evaluate to true when passed to !!. So checking !!obj or !![] won’t work – you need to check properties and lengths instead.

Comparison to Boolean()

JavaScript also provides a Boolean() function that can convert values to Booleans:

Boolean(0) // false 
Boolean(1) // true
JavaScript

So when should you use !! vs Boolean()?

The !! operator gives you a quick shorthand for converting to Boolean without calling a function. But functionally, !! and Boolean() work the same in converting values.

However, there are some differences:

  • !! performs faster than Boolean()
  • Boolean() will show up in stack traces, !! is harder to debug
  • Boolean() is easier to search for than !!

Overall !! is generally preferred over Boolean() for most use cases. The performance boost and brevity of !! make it the better choice in most situations.

Use Cases for !!

Now that we’ve explored what the !! operator does, let’s look at some of the most common use cases and examples.

Simplifying Conditionals

Double NOT is commonly used to simplify conditional checks:

// Longhand 
if (x !== null || x !== undefined || x !== '') {
  // do something 
}

// Simplified with !!
if (!!x) {
  // do something
}
JavaScript

This avoids repetitive null/undefined checks.

Parsing User Input

When retrieving user input, double NOT can help ensure you have a Boolean value:

const rememberMe = !!req.body.rememberMe; 

if (rememberMe) {
  // set cookie
}
JavaScript

This converts any value from the form to a definitive true or false.

Empty Object/Array Checks

To check if an object or array has any contents:

const arr = [];
if (!!arr.length) {
  // array is not empty
}

const obj = {};
if (!!Object.keys(obj).length) {
  // object is not empty
}
JavaScript

Fallback/Default Variables

You can use !! to fallback to a default value if the desired value is falsey:

const name = user.name || 'Guest';
const displayName = !!name || 'Anonymous';
JavaScript

If name is empty, displayName will be ‘Anonymous’.

Toggle Functionality

The !! operator can be used to “toggle” functionality in code:

let debug = false;

function log(msg) {
  if (!!debug) {
    console.log(msg);
  }
}
JavaScript

Toggling debug to true will enable logging.

Common Mistakes

While the !! the operator is very useful in JavaScript, there are some mistakes and misuse to watch out for:

  • Accidentally coercing non-Boolean values like strings:
// Wrong, converts 'false' string to true
!!user.wantsEmails
JavaScript
Checking equality against true or false instead of using !!:

JavaScript

Overusing !!instead of letting JavaScript implicitly coerce values:

// Unnecessary !!
if (!!x > 10) { ... }

// Simpler
if (x > 10) { ... }
JavaScript
  • Forgetting that !!obj and !![] still evaluate to true for empty collections.

Being mindful of these potential pitfalls will help you avoid misusing JavaScript’s !! operator.

Key Takeaways

To recap our guide to JavaScript’s double exclamation mark:

  • !! converts any value to a Boolean true or false
  • This allows simplifying conditionals, evaluating user input, and other use cases
  • !! can check if a value is “empty” like null or empty string/array/object
  • It provides a shortcut over Boolean() but works similarly
  • Take care to avoid common mistakes like accidental coercion

With an understanding of how !! works and when to use it, you can take advantage of this short but extremely useful JavaScript operator. Double exclamation marks may seem obscure, but are actually a handy tool for any JavaScript developer.

Frequently Asked Questions

What is the official name of the !! operator?

The official name is the double NOT bitwise operator. NOT ! is the JavaScript unary negation operator, and two NOTs (!!) together form the double NOT operator.

What is the difference between !! and Boolean()?

!! and Boolean() both convert values to Boolean true or false. The main differences are that !! performs faster and is more concise, while Boolean() is easier to debug and search for in code.

Does !! work for checking if arrays or objects are empty?

No, !!obj and !![] will evaluate to true even for empty objects and arrays. To check emptiness, you need to check properties like !!obj.length or !!Object.keys(obj).length.

Is !! the same as == true or === true?

No, !!value simply converts to a Boolean, while value == true and value === true check if value is strictly equal to true. !! is generally preferred over equality checks.

What is the ! operator in JavaScript?

The ! operator is the NOT logical operator. It converts any value to the inverse of its Boolean equivalent (not false becomes true, etc). A single ! performs logical negation, while !! doubles the NOT operators.

Leave a Comment