I wonder if there is a better way to write this.
if ( num == 0 || num == 20 || num == 32 ) {
// execute
}
Would it be better to use case? or loop the condition?
Prefered language is Javascript, then any language will do.
I wonder if there is a better way to write this.
if ( num == 0 || num == 20 || num == 32 ) {
// execute
}
Would it be better to use case? or loop the condition?
Prefered language is Javascript, then any language will do.
In JavaScript you can write this instead:
if ([0, 2, 32].includes(num)) {
// execute
}
Or
let some_array = [0, 2, 32]
// more code
if (some_array.includes(num)) {
// execute
}
if the list of cases might change, especially if the exact set of options is a function of user actions. And then you might use an if-else statement, e.g.
let some_array = [0, 2, 32]
// more code
if (some_array.includes(num)) {
// execute
} else
// execute else
}
or more complex if else trees. But in any case Array.prototype.includes is a great option for something like this. It’s very flexible, maintainable, and easy to read. And much more powerful—-you can fetch the array of options from database using a REST call, or build it from user input, you can filter it based on user-supplied filters. All things that would be much harder to do if you test for each possible value by itself one at a time.