Dev
Dev

Reputation: 423

NodeJS double negate ternary operator

I am using ternary operator in NodeJS below shown

let err = {a: 10, message: 0}
const error = !!err.message ? err.message : err;

But above code is showing eslint error for double negation how to solve this ? below alternative is same as above

const error = err.message ? err.message : err;

Upvotes: 1

Views: 653

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370779

You can avoid the conditional operator entirely if you want - if err.message is falsey, just alternate with err:

const error = err.message || err;

Upvotes: 5

Jack Bashford
Jack Bashford

Reputation: 44107

There's no actual need to use the !! - this code is what you want:

const error = err.message ? err.message : err;

If you really wanted to check against a Boolean rather than the pure value:

const error = Boolean(err.message) ? err.message : err;

Also note that what you're doing - if err.message is truthy, use it, or use err - is the exact use case of the logical OR operator ||:

const err = err.message || err;

Upvotes: 6

Related Questions