Correct way to use || with javascript strings

I need to check if a javascript variable contains one of two possible values. This is incorrect, I know, so a point in the right direction would be much appreciated. Thanks in advance

if (state.code === (‘CLAIM-000’ || ‘CLAIM-009’)) {

}

No you have to repeat the check…

if ((state.code === 'CLAIM-000') || (state.code === 'CLAIM-009')) {
...
}

If you are looking to have it check more than two, this is obviously going to get long and tedious. At which point you would be better off putting your strings into something like an array and then search the array of strings.

:slight_smile:

1 Like

That completely makes sense @Martyr2. Thank you for the boost.

With strings I prefer to use regular expressions

if(/^CLAIM-000$/.test(state.code) || /^CLAIM-009$/.test(state.code)) {}

Would that regular expression be easier to understand as one condition?

if(/^CLAIM-00[09]$/.test(state.code)) {

}

or

if(/^CLAIM-(000|009)$/.test(state.code)) {

}
1 Like

Alternate suggestion:

if ( ['CLAIM-000','CLAIM-009'].includes(state.code)) {
  // execute true condition code
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.