I have several if statements in my script which require a lot of conditions and I would like to write them in the more efficient way and with "shorthand notation" for the readability.
For example, I have this if statement:
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
/*** some code ***/
}
So I have written it in with indexOf and array but i'm not sure if it's the best way:
if (['abc', 'def', 'ghi' ,'jkl'].indexOf(x) > -1) {
/*** some code ***/
}
I'm near sure there are some other methods more cleaner and fastest...
Your array is readable and easy to modify. It also gives you the ability to take the array as a parameter if you later chose to do so.
If you're using ES6, you may want to use Array.prototype.includes
:
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
/*** some code ***/
}
Worrying about performance in this case would be a premature optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With