Readable JavaScript conditions (#note)

Chris Ferdinandi, the vanilla JavaScript guy, published an excellent coding tip to make your JavaScript conditions more readable.
Suppose you have a condition like the following:
if (wizard === ‘Merlin’ || wizard === ‘Gandalf’) {


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

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

Suppose you have a condition like the following:

if (wizard === 'Merlin' || wizard === 'Gandalf') {
  // ...
}

My mind needs a moment to process this if. Additionally, the condition becomes harder to read if there are more wizards and you have to chain all these logical ORs.

And now look at what Chris advises to use instead:

if (['Merlin', 'Gandalf'].includes(wizard)) {
  // ...
}

Is that readable code, or what? 😲 The condition even includes the word include 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.


Reply to Stefan


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis


Print Share Comment Cite Upload Translate Updates
APA

Stefan Judis | Sciencx (2022-02-22T23:00:00+00:00) Readable JavaScript conditions (#note). Retrieved from https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/

MLA
" » Readable JavaScript conditions (#note)." Stefan Judis | Sciencx - Tuesday February 22, 2022, https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/
HARVARD
Stefan Judis | Sciencx Tuesday February 22, 2022 » Readable JavaScript conditions (#note)., viewed ,<https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/>
VANCOUVER
Stefan Judis | Sciencx - » Readable JavaScript conditions (#note). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/
CHICAGO
" » Readable JavaScript conditions (#note)." Stefan Judis | Sciencx - Accessed . https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/
IEEE
" » Readable JavaScript conditions (#note)." Stefan Judis | Sciencx [Online]. Available: https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/. [Accessed: ]
rf:citation
» Readable JavaScript conditions (#note) | Stefan Judis | Sciencx | https://www.scien.cx/2022/02/22/readable-javascript-conditions-note/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.