Javascript - if an expression with multiple conditions in a shorthand

I have several if statements in my script that require a lot of conditions, and I would like to write them in a more efficient way and with a “shorthand notation” for readability.

For example, I have an if statement:

if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    /*** some code ***/
}

So, I wrote it using indexOf and an array, but I'm not sure if this is the best way:

if (['abc', 'def', 'ghi' ,'jkl'].indexOf(x) > -1) {
   /*** some code ***/
}

I am pretty sure there are other methods cleaner and faster ...

+4
source share
2 answers

Your array is readable and easy to modify. It also gives you the option to accept an array as a parameter if you later decide to do this.

ES6, Array.prototype.includes:

if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   /*** some code ***/
}

.

+3

. , ?

x === 'a' || x === 'b' || x === 'c' || x ==='d'

['a', 'b', 'c' ,'d'].indexOf(x) > -1

, , . , ,

:

isSpecialLetter = function (x){
  return x === 'a' || x === 'b' || x === 'c' || x ==='d';
}

if(isSpecialLetter(x)){
//More code
}
0

Source: https://habr.com/ru/post/1662700/


All Articles