Monday, December 13, 2021

Javascript: Guard clauses and avoiding using 'else'

Guard clauses

“In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.”

— Wikipedia

Let’s take a look at an example. We have a function, getValidCandidate, which checks if a candidate is valid, provided a list of members and returns the member if the candidate is valid, or undeļ¬ned otherwise.

Look how nested the code is? Ifs wrapping other ifs, nested 3 times. Let’s rewrite this and use guard clauses instead.

Guard clauses prevent the function from continuing what it’s doing and instead returning early if the guarding condition is not met. Naturally, we also know that the end result is the last return of the function.

Skip the ‘else’ part

Whenever you’re about to write else, stop and reconsider what you’re doing and search for an alternative way to express the logic.

Let’s cover a few ways that we can avoid using else. One of them is guard clauses, which we just covered above. Another approach is using default values. Let’s take an example.

Let’s say we have a function, negateOdd, which takes a number and negates it if the number is odd.

The function does what it’s supposed to. But it’s unnecessarily using an else. Let’s refactor it, and instead, use a default value.

We now assign result with a default value, and the variable will only be changed if the condition in the if-statement is met. But let’s do even better. We’re supposed to question the use of let and imperative (altering the state of your program step by step) code. Let’s see if we can make this function even more readable and concise.

There is a version of if-else that is generally accepted. It’s the ternary operator.

Share This:    Facebook Twitter

0 comments:

Post a Comment

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top