Search code examples
javascriptecmascript-6booleaneslinttype-coercion

Why use '!!' before an expression?


I'm on VSCode with ESLint installed and I tried to type that expression to get a "true" or "false" output

const result = goodGuys.includes(guy) ?

but it didn't worked and with a quick fix (from ESLint that I don't understand, so here I am lol) of removing the "?" and adding two exclamation marks at the beginning, it work just well.

const result = !!goodGuys.includes(guy);

Can someone explain this to me please? Thx


Solution

  • That's just an ESLint thing. includes returns a Boolean, so it actually functions like that in code. ESLint sometimes wants to enforce Boolean rules, so !! does that for you. It works by using double negation - once to get an inverted Boolean, then again to un-invert it, giving you the Boolean representation of your expression. It's basically the same as this:

    const result = Boolean(goodGuys.includes(guy));