Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - if statement with several conditions in shorthand notation

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...

like image 876
freaky Avatar asked Mar 10 '23 12:03

freaky


1 Answers

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.

like image 67
4castle Avatar answered Apr 06 '23 14:04

4castle