I need to evaluate a variable and check if it's equal to one of two other variables.
I do it like this:
if (a == b || a == c)
{
}
I feel there's got to be a better way to evaluate variables in this manner. Is there?
I need to evaluate a variable and check if it's equal to one of two other variables.
I do it like this:
if (a == b || a == c)
{
}
I feel there's got to be a better way to evaluate variables in this manner. Is there?
You can also use Array.prototype.includes
(ES7).
if ([b, c, d, e].includes(a)) {
// do stuff
}
If you're just comparing one value to 2 others, this is the most efficient and elegant solution. No need to change anything!
If you want to see whether one variable is equal to any of a larger collection of other variables you can do something like:
if(([b,c,d,e,f].indexOf(a) !== -1) {
// "a" is equal to either b, c, d, e, or f
}
The indexOf
method may not be available in older browsers so be sure to check for it! In legacy browsers you can use write your own method to search through the array or utilize any popular general-use library... most will have this functionality.
.. And if you have many variables to compare against, you could probably use this:
if ([a,b,c,d,e,f,g,h].indexOf(yourValue) >= 0)
There's one more way of doing it, that is in case you are willing to do a little more typing:
if (yourValue in {a:0,b:0, c:0, ... })
or may be you could have a function that returns the object version of the array:
var wrap = function(){
var obj = {};
for (var i=0; i<arguments.length; i++)
obj[arguments[i]]=0;
return obj;
};
and then:
if (yourValue in wrap(a,b,c,d,e,f,g))
If you are fine with jQuery, you could use jQuery's way:
$.inArray(yourValue, [a,b,c,d,e,f])
I think that what you have above is the most straightforward option.
Also, in JavaScript there are different kinds of equal operators. The ==
equal operator returns a boolean true if both the operands are equal. JavaScript will attempt to convert different data types to the same type in order to make the comparison. The ===
operator is the strict equal operator and only returns a Boolean true if both the operands are equal and of the same type.
var values = [b,c,d,e,f];
for (var i=0,n=values.length; i<n; i++){
if (values[i] == a){
// ...
break;
}
}