Friday, May 3, 2024
HomeJavaScriptLearn how to write extra readable JavaScript conditionals

Learn how to write extra readable JavaScript conditionals


One of many practices of unpolluted code is to make it extra readable. And a reasonably widespread use case in code bases is conditionals. I just lately got here throughout a approach of writing extra readable JavaScript conditionals and considered sharing it with everybody.

Take into account the next conditional:

– Commercial –

if (noteType === CallNoteType.Remark || noteType === CallNoteType.Textual content) {
}

The thoughts takes a couple of minutes to course of the “if” conditionals. And it might be much less readable if there have been extra notice varieties that we had been checking for.

As a substitute of chaining all of the logical ORs, we are able to make use of the contains technique on an array to get extra readable JavaScript conditionals.

if ([CallNoteType.Comment, CallNoteType.Text].contains(noteType)) {
}

// or use a variable 
// to make it even clearer
if (editableNoteTypes.contains(noteType)) {
}

It seems to be like a tiny change however tremendously improves readability!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments