Luis Febro
Luis Febro

Reputation: 1860

Is it redundant using !! boolean structure when the value is either true or false?

There are other questions about !! (double negation) already (here, and here), and these questions answer my confusion about this. But what I want to know with this question is more specific... Here it is my case.

I have eslint set on my codebase, and I fixed all fixable errors recently.

One of these fixes including the double exclamation sign negation.

One example before the fix and after:

// BEFORE eslint fix:
import { IS_DEV } from "./config/clientUrl";
const sandboxMode = IS_DEV ? true : false;
// AFTER eslint fix:
import { IS_DEV } from "./config/clientUrl";
const sandboxMode = !!IS_DEV;

The fix was correct in detect that it was redundant since is IS_DEV is already a boolean here. So I know the value is either true or false.

So, is there any difference using double negation like this:

const sandboxMode = !!IS_DEV;

and using simply without it:

const sandboxMode = IS_DEV;

This wouldn't be another redundancy in this case?

Upvotes: 0

Views: 1207

Answers (1)

Freddy
Freddy

Reputation: 1229

A few points to my answer:

  • If you know for sure that IS_DEV will be either true or false (a boolean) and NEVER anything else, you can just use this: const sandboxMode = IS_DEV
  • If it's possible that IS_DEV is going to not be set (thus being undefined), you should use const sandboxMode = !!IS_DEV which will force sandboxMode to be a boolean
  • But it also depends on how sandboxMode is being consumed!

Upvotes: 1

Related Questions