0

I saw a comparison like the following in a question on SO:

(pNum != ('2','3','4','5','6','7','8','9'))

The OP has been trying to check if a number falls in a certain range but this code is inaccurate as it will always compare with right most value inside the brace(i.e. 9) This means when pNum = 2 the comparison will return true and not false as was expected by OP who was expecting it to work like inArray or in.

My question is whether this sort of comparison is going to be useful in any real case in any scenario?

Nisarg
  • 13,121
  • 5
  • 31
  • 48
techie_28
  • 2,025
  • 4
  • 37
  • 56

1 Answers1

0

My question is whether this sort of comparison is going to be useful in any real case in any scenario?

No. As you observe, the comparison only compares the last item inside the bracket. So all it can accomplish is to confuse the reader.

If you intend to compare a variable with a set of values, you could use array#includes or array#indexOf >= 0. Something like:

console.log(['2','3','4','5','6','7','8','9'].includes('2'));
console.log(['2','3','4','5','6','7','8','9'].includes('6'));
console.log(['2','3','4','5','6','7','8','9'].includes('9'));

// IE 
console.log(['2','3','4','5','6','7','8','9'].indexOf('2') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('6') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('9') >= 0);
Nisarg
  • 13,121
  • 5
  • 31
  • 48