I have JavaScript code in my app that checks values using the OR(||) condition as in code snippet below. The number of OR conditions is not small in most of my code.
Question: Is there a way to make the code that has many multiple OR conditions more concise by using something like this:value IN ('s','b','g','p','z')
? I was interested in something that comes as close as possible to an IN clause.
if(value === "s" || value === "b" || value === "g" || value === "p" || value === "z") {
//do something
}
The simplest way is to create an array of valid values, then make sure your value is in that list. You can use the indexOf
method for that:
var allowed = ['s', 'b', 'g', 'p', 'z'];
if (allowed.indexOf(value) !== -1) {
// do something
}
The ES6 standard introduces Sets, which has a has
method to do a similar thing on unique values.
This will work for strings, numbers, and other simple non-object values. Comparing objects with ===
will only succeed if the array/set already contains the exact same object.
You could do something like this:
var values = ['s','b','g','p','z'];
if (values.indexOf(value) > -1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With