Cleaning up Your JavaScript Code: The Double Bang (!!) Operator

Hero image for Cleaning up Your JavaScript Code: The Double Bang (!!) Operator. Image by Vecteezy.
Hero image for 'Cleaning up Your JavaScript Code: The Double Bang (!!) Operator.' Image by Vecteezy.

Boolean and truthy/falsy values can seem simple at first, but they can be deceptively complex in certain languages. For instance, JavaScript has six different types of "falsy" values and if you're working in a strict setting or trying to make your code bulletproof (as we all should be), it's easy to get tripped up by them.

This can lead to developers becoming overcautious, which can lead to noisy, messy, or unnecessary code. When it comes to boolean typecasting, the doublebang operator is a particular culprit.


What is the Double‑Bang Operator in JavaScript?

While inheriting older codebases, or even working on a fresh build, you might see or use two consecutive exclamation marks: !!. This is the doublebang operator, and it can be used to typecast values to a strict boolean value (either true or false).

In JavaScript which already supports truthy/falsy values the doublebang operator can be more easily thought of as two not operators in a row (it is sometimes called the "doublenot" operator for this reason). Here's how it works:

The first notoperator (!) takes any piece of data, and typecasts it into a boolean value. However, when it does this, it as you would expect flips the value. For instance, a value with "true" as a string would be converted to a false boolean:

!("true") === false

When you look at it like this, it is a little confusing. So, the second notoperator is then used to flip the value back to what a developer would expect. So in this example, the string "true" would result in a true boolean value:

!!("true") === true

This is confusing, so the second notoperator is used to flip the value back to what a developer would expect in this example, the string "true" would result in a true boolean value. Handy! Or is it?


When Would You Use the Double‑Bang Operator in JavaScript?

As a developer working with JavaScript, I'm sure you've written your fair share of if statements for all manner of different pieces of logic. I'm sure too that a lot of the time, you use if to determine whether a variable has any data in it or not. In my bad old days of developing with jQuery, the equivalent would have been to check .length to determine whether a piece of data existed and had anything in it.

However, in situations like this, you want to be checking against a definitive boolean true/false value, which is where the doublebang operator can become extremely useful. The problem stems from the way that Javascript natively and naturally handles truthy/falsy values; when you run an if statement against a variable, JavaScript will by default handle null, 0, false or empty strings and treat them as falsy values. If there is data present, it will treat it as a truthy value. For example:

const variable = 'foo';if (!!exampleVariable) {  // exampleVariable is true} else {  // exampleVariable is false}

This is pretty clear, right? It takes exampleVariable, typecasts it to a boolean and tests it. Easy, and clear. But this code could in most cases just as easily be written as:

const variable = 'foo';if (exampleVariable) {  // exampleVariable is true} else {  // exampleVariable is false}

JavaScript already handles truthy/falsy values pretty well. It's not a huge change, but it's a little clearer, a little cleaner, and it's fewer characters. This goes for ternary expressions, too, because they're just condensed if statements. Take a look:

const bar = !!exampleVariable ? exampleVariable : 'exampleVariable is false';

This code will typecast exampleVariable to a strict boolean, and then either assign it to the variable bar if it is true, or assign a string to that variable if it isn't. Again, this isn't always necessary here's a neater refactor:

const bar = (exampleVariable || 'exampleVariable is false');

Here, we've even taken things one step further by using the or operator to really cut through the mess and keep our code DRY. Much, much nicer.


Should You Ever Use the Double‑Bang Operator?

Fundamentally, what !! is doing is typecasting a variable (potentially even a nonexistent one) to a boolean, which is particularly useful if you are dealing with data of uncertain type or source, or if the return may otherwise be a nonboolean Object.

Taking an example from Stack Overflow, consider detecting versions of Internet Explorer:

const isIE8 = navigator.userAgent.match(/MSIE 8.0/);console.log(isIE8);    // returns type of either Array or nullconsole.log(!!isIE8); //returns a boolean: true or false

So, whilst JavaScript will generally handle truthy/falsy values within an if statement, if you want to explicitly return a boolean from a function, based on the value (or very existence) of a variable, then using the doublebang !! (or even triplebang !!!) offers a level of failsafe in environments where you may need strict boolean values.

It can also be handy if you want to be very verbose and clear with your code if you're writing something that expects a boolean value, or returns a boolean value, it can be pretty useful to indicate to other developers working on your codebase that this is the case. It's an operator that can be used as shorthand to let other developers know how a function works or what it's expecting, or to make absolutely certain that the values you are handling are the format you need.


Categories:

  1. Development
  2. Front‑End Development
  3. JavaScript