Are there only ever those 6 possibilities? If yes, then the new one should be fine
Best way to write if statements
I'm currently migrating an old project and in the code they do this statement
if (question.response_type === "boolean") {
//action
} else if (
question.response_type !== "list" &&
question.response_type !== "multiple" &&
question.response_type !== "image" &&
question.response_type !== "text"
) {
//action
}
Usually I would do it like this
if (question.response_type === "boolean") {
//action
} else if (
question.response_type === "date" ||
question.response_type === "numeric"
) {
//action
}
My question is does it matter which way I do it and is there a difference?
In theory there should be a minuscule difference as in one snippet you are doing 4 comparisons and in the other you are doing two.
But that would very tiny, and unnoticeable. So I would stick with the one that communicates the code intention better.
When testing multiple options like this I usually go with in_array(...) in PHP, or .includes() in JS, like this:
if (question.response_type === "boolean") {
//action
} else if ( ! ['list', 'multiple', 'image', 'text'].includes(question.response_type) ) {
//action
}
or
if (question.response_type === "boolean") {
//action
} else if (['date', 'numeric'].includes(question.response_type) ) {
//action
}
This way if you need to remove or add a new type into check you just need to add/remove it from the array.
I personally prefer the second one as I find affirmative conditions easier to read in cases like this.
Please or to participate in this conversation.