Readable JavaScript conditions
- 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!
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.
Related Topics
Related Articles
- How to create an API wrapper using a JavaScript proxy
- "fetch" supports a "keepAlive" option to make it outlive page navigations
- A clipboard magic trick - how to use different MIME types with the Clipboard API
- Keyboard button clicks with Space and Enter behave differently
- VS Code supports JSDoc-powered type checking