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...
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...
switch
– CrayonViolent
Commented
Dec 3, 2016 at 0:15
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.
This is really a question of readability. What will make the most sense when you're reading the same code in five months?
x === 'a' || x === 'b' || x === 'c' || x ==='d'
or
['a', 'b', 'c' ,'d'].indexOf(x) > -1
I would use the long 'or' expression, since it very clearly and explicitly tells you what the code is doing. However, I'd wrap that expression in a function to make the rest of the code more readable
Example:
isSpecialLetter = function (x){
return x === 'a' || x === 'b' || x === 'c' || x ==='d';
}
if(isSpecialLetter(x)){
//More code
}
If you have to use ES5 then
if(~['abc', 'def', 'ghi' ,'jkl'].indexOf(x)) {...}
or a bit more expressive
if(!!~['abc', 'def', 'ghi' ,'jkl'].indexOf(x)) {...}