Published at
Updated at
Reading time
1min

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 6 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles