Piotr Gajek
written byPiotr Gajek
posted on December 8, 2023
Technical Architect and Full-stack Salesforce Developer. He started his adventure with Salesforce in 2017. Clean code lover and thoughtful solutions enthusiast.

Do not use Ternary operator to return Boolean

do-not-use-ternary-operator-to-return-boolean

Introduction

All comperation statements either in Apex or LWC return Boolean. Let’s take a look for an examples.

LWC

'a' === 'b' // => false
1 === 1 // => true

Apex

'a' == 'b' // => false
1 == 1 // => true

Issue

There is no need to use the ternary operator since the comparison statement returns a Boolean.

❌❌❌

const isPartner = this.userType === 'Partner' ? true : false;
const isCustomer = this.userType === 'Partner' ? false : true;

Based on the documentation:

condition ? exprIfTrue : exprIfFalse;

You have something like this:

condition that evaluates to Boolean (condition) ? true (exprIfTrue) : false (exprIfFalse);
true (condition that evaluates to Boolean) ? true : false;
false (condition that evaluates to Boolean) ? true : false;

Best Practice

  • this.userType === 'Partner' is comperation statement.
  • A comparison statement inherently returns a Boolean value.
  • Therefore, there is no need to use the Ternary operator, since the result is already true or false.

Based on the KISS principle your code can be as simple as possible.

✅✅✅

const isPartner = this.userType === 'Partner';
const isCustomer = this.userType !== 'Partner';

Do not use Ternary operator to return Boolean


If you have any questions feel free to ask in the comment section below. 🙂

Was it helpful? Check out our other great posts here.


References

Buy Me A Coffee