Artboard 16light, inspiration, solution, idea, innovation,ionicons-v5_logosGoogle Sheets iconSwift icon
Published at
Updated at
Reading time
1min
This post is a note that includes my thoughts about something I found online. Check it out yourself!

Chris Ferdinandi, the vanilla JavaScript guy, published an excellent coding tip to make your JavaScript conditions more readable.

Suppose you have the following condition:

if (fruit === 'apple' || fruit === 'strawberry') {
  // ...
}

My mind needs a moment to process this if. It's just not easy to read. And additionally, the condition becomes even harder to read if there are more fruits and you have to chain all these logical ORs.

And now look at what Chris advises to use instead:

if (['apple', 'strawberry'].includes(fruit)) {
  // ...
}

// or even place things in a variable 
// to make it even clearer
if (deliciousFruits.includes(fruit)) {
  // ...
}

Is that readable code, or what? ๐Ÿ˜ฒ The condition even includes the word includes to make it easier to understand! ๐Ÿ‘ It's a tiny change that improves readability tremendously.

I'll adopt this pattern from now on! Thanks, Chris.

Was this post helpful?
Yes? Cool! You might want to check out Web Weekly for more WebDev shenanigans. The last edition went out 11 days ago.

Related Topics

Related Articles