0

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?

Luis Febro
  • 1,733
  • 1
  • 16
  • 21
  • 1
    I think it's completely harmless and it makes the code readable: an experienced JavaScript programmer would recognize that you're creating a `true` or `false` value. – Pointy Feb 27 '21 at 14:21
  • 4
    It is redundant if you know `IS_DEV` is Boolean. But then so of course is your original. Eslint doesn't know the type though, and for a value of unknown type your "fixed" version is much more idiomatic than the original ternary. – Robin Zigmond Feb 27 '21 at 14:23

1 Answers1

1

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!
Freddy
  • 1,229
  • 2
  • 13
  • 22