-1

Is there a function/method to evaluate whether a value evaluates to true or false in javascript? If not, is the following a good substitute?

const toBool = (x) => x ? true : false;
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • There isn't one because it isn't necessary - just use JS's falsyness naturally (or the `!!x` idiom). How does this `toBool` function improve JS programs at all? It doesn't make them any more readable nor more maintainable - this adds zero value, in my opinion. – Dai Oct 08 '21 at 23:57
  • 1
    @Dai There is use cases for this, but I agree if you're just planning on using it like: `if (toBool(x))` it doesn't make sense, but there are cases where you need a true/false rather than truthy value. – ᴓᴓᴓ Oct 09 '21 at 00:01
  • 2
    Couple ways: `Boolean(x)` will convert to boolean (be sure not to use new). So will `!!x`. Note that as the other comment suggests it is rarely necessary to do this. Unless we're talking about Typescript. – Jared Smith Oct 09 '21 at 00:01
  • @JaredSmith TypeScript supports `!!x` though - and using `Boolean(x)` as you suggest is also equivalent to this `toBool` though. – Dai Oct 09 '21 at 00:25
  • @dai meant more that unlike JS, TS actually cares about whether something is boolean or just truthy/falsey – Jared Smith Oct 09 '21 at 00:37

1 Answers1

1

Your ternary is fine. An alternative is const toBool = (x) => !!x;

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18