Skip to content Skip to sidebar Skip to footer

Can You Shorten An 'if' Statement Where A Certain Variable Could Be Multiple Things

Since I sometimes needs an if-statement like if (variable == 'one' || variable == 'two' || variable == 'three') { // code } I was wondering if you could write this any shorte

Solution 1:

or ..

if (~['one', 'two', 'three'].indexOf(variable))

any cat with many ways to skin it

~ is bitwise NOT ... so -1 becomes 0, 0 becomes -1, 1 becomes -2 and so on

so ... ~ with indexOf is "truthy" when indexOf is 0 or greater, i.e. value is found ...

basically it's a shortcut that I probably wouldn't use in code expected to be read by other people as over half would scratch their heads and wonder what the code did :p

Solution 2:

You could try:

if(variable in {one:1, two:1, three:1})

or:

if(['one', 'two', 'three'].indexOf(variable) > -1)

or in ES6 (works natively in most recent browsers now):

if(newSet(['one', 'two', 'three']).has(variable))

Note that solution 2 will scale linearly with the size of the array, so it's not a good idea if you have more than a few values to check against.

Solution 3:

No, there is no shortcut for such multiple comparisons. If you try it, it will calculate the value of the expression ('one' || 'two' || 'three') and then compare that to the variable.

You can put the values in an array and look for it:

if ([ 'one', 'two', 'three' ].indexOf(variable) != -1) {
    // code
}

You can use a switch:

switch (variable) {
  case'one':
  case'two':
  case'three':
    // code
}

You can look for the values among object properties (but the object values are just dummies to allow the properties to exist):

if (varible in { 'one': 1, 'two': 1, 'three': 1 }) {
    // code
}

Post a Comment for "Can You Shorten An 'if' Statement Where A Certain Variable Could Be Multiple Things"