-1

Authorization code example

    const refreshTokens = await db.RefreshToken.find({ user: user.id });
    req.user.ownsToken = token => !!refreshTokens.find(x => x.token === token);
    next();

What does !! actually, do?

MikiBelavista
  • 2,470
  • 10
  • 48
  • 70
  • Checks if the value is truthy or falsy. https://www.sitepoint.com/javascript-truthy-falsy/ – Ana Svitlica Sep 30 '20 at 09:06
  • In this case it would make more sense to use [`.some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) instead of [`.find()`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). – Ivar Sep 30 '20 at 09:13
  • @AnaSvitlica Which values are compared in this example? – MikiBelavista Sep 30 '20 at 09:14
  • 1
    In your example it checks if the result of `.find()` function is a falsy value (`null, undefined, 0, '', "", false, NaN`). So !! will give you false if the value of `.find()` is falsy. – Ana Svitlica Sep 30 '20 at 09:18
  • 1
    You can open console in your browser and type something like `!![]` or `!!null` if you're unsure what it returns for certain values. – Ana Svitlica Sep 30 '20 at 09:20

1 Answers1

1

Any value can be converted to a real Boolean value using a double-negative

!! to be absolutely certain a false is generated only by false, 0, "", null, undefined and NaN:

// instead of
if (x === y) // ...
// runs if x and y are identical...
// except when both are NaN

// use
if (!!x === !!y) // ...
// runs if x and y are identical...
// including when either or both are NaN
Safvan CK
  • 1,140
  • 9
  • 18