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.
Was this post helpful?
Yes? Cool! You might want to check out Web Weekly for more WebDev shenanigans. The last edition went out 24 days ago.
Yes? Cool! You might want to check out Web Weekly for more WebDev shenanigans. The last edition went out 24 days ago.