Piotr Gajek
ByPiotr Gajek
Senior Salesforce Developer
December 8, 2023 Loading views...
shareLinkedIn iconFacebook iconTwitter icon

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

Piotr Gajek
Piotr Gajek
Senior Salesforce Developer
Technical Architect and Full-stack Salesforce Developer. He started his adventure with Salesforce in 2017. Clean code lover and thoughtful solutions enthusiast.

You might also like

Salesforce Naming Convention
January 5, 2024

Salesforce Naming Convention

In programming, naming conventions are crucial for clarity and collaboration. Choose intention-revealing names, avoid ambiguity, and maintain consistency to enhance code readability and convey meaningful context to fellow developers.

Piotr Gajek
Piotr Gajek

Senior Salesforce Developer