Sign up to receive SuiteScript examples and advice directly in your email inbox.

Comparing to multiple values

Created: October 19, 2020

Thanks to everyone who responded to my inquiry about potential source control content. Your help and insight ensures I'm able to offer useful, valuable content.

Here's a really common mistake I see a lot of newer JavaScript/SuiteScript developers making. It's quite often that you'll need to check whether a field value matches one of several possible values that you care about.

Let's say you want to do something important for every Customer with a first name of Tom, Aryn, Lovell, or Jaron. Here's the first attempt I often see for that sort of comparison:

function firstNameMatches (firstName) {
  if (firstName === ('Tom' || 'Aryn' || 'Lovell' || 'Jaron')) {
    return true
  } else {
    return false
  }
}

While logically this might seem reasonable, it shows a misunderstanding of how the || operator works. The || operator IS NOT how you create lists of values in JavaScript. You're actually looking for an Array.

Arrays create lists of values and provide methods for asking "Is a specific value within the Array?". The first step is to store our list of possible values as an Array, not as a boolean expression like you see above.

Next, we can use an Array method to determine whether our value is contained within the Array. In SuiteScript 2.0 (which is ECMAScript version 5.1), we can use the indexOf method. As its name might imply, this method returns the index of a given value if it occurs within the Array; if the value does not occur within the Array, then it returns -1. So in SuiteScript 2.0, we can do something like:

function firstNameMatches (firstName) {
  const importantValues = ['Tom', 'Aryn', 'Lovell', 'Jaron']
  if (importantValues.indexOf(firstName) >= 0) {
    return true
  } else {
    return false
  }
}

In SuiteScript 2.1 (which is ECMAScript 2019), we can use the includes method. This is a little cleaner as it removes the need to compare against a number. The method returns true if the given value occurs in the Array and false if the value does not occur within the Array. In SuiteScript 2.1, we can do something like:

function firstNameMatches (firstName) {
  const importantValues = ['Tom', 'Aryn', 'Lovell', 'Jaron']
  if (importantValues.includes(firstName)) {
    return true
  } else {
    return false
  }
}

As an added bonus, since the only thing the if..else branches do is return the corresponding boolean value, you can reduce to simply returning the comparison result:

function firstNameMatches (firstName) {
  const importantValues = ['Tom', 'Aryn', 'Lovell', 'Jaron']
  return importantValues.includes(firstName)
}

If you'd like to improve your logical deduction and reduction capabilities, Boolean Algebra is a worthwhile area of study - as if you needed more homework.