0

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.

  • As far as I am aware that is the most efficient and portable way. – Dmytro Jul 03 '22 at 01:12
  • https://stackoverflow.com/questions/427760/when-to-use-if-else-if-else-over-switch-statements-and-vice-versa#:~:text=Use%20switch%20every%20time%20you,on%20where%20to%20use%20each. – Pran Kumar Sarkar Jul 03 '22 at 05:49
  • There are options besides if and switch though. See my answer for another option. – bob Jul 03 '22 at 13:36

1 Answers1

1

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.

bob
  • 419
  • 4
  • 11