Readable JavaScript conditions
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
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.
If you enjoyed this article...
Join 5.5k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.