loading...

More readable conditional with Array.includes()

gabrielrufino profile image Gabriel Rufino ・1 min read

Do you know the function Array.includes() of the JavaScript? This function was specified in ES7 and is capable of making a conditional much more readable.

This function determines is the parameter is contained in the array.

const numbers = [1, 2, 3, 4]
const strings = ['Gabriel', 'Rufino']

numbers.includes(3) // true
numbers.includes(6) // false
strings.includes('Rufino') // true
strings.includes('Fernando') // false

Knowing this function, you can now write more readable conditionals that compare a variable with many possibilities by replacing large chains of or operator (||) with Array.includes() using a variable as the parameter. See the example:

Using or operator

function get(request, response) {
  const access = request.access

  if (access === 'maintainer' || access === 'admin' || access === 'developer') {
    return response.json({ allowed: true })
  } else {
    return response.json({ allowed: false })
  }
}

Using Array.includes()

function get(request, response) {
  const access = request.access

  if (['maintainer', 'admin', 'developer'].includes(access)) {
    return response.json({ allowed: true })
  } else {
    return response.json({ allowed: false })
  }
}

Works with NaN

NaN === NaN // false
[1, 2, 3, NaN].includes(NaN) // true

Thanks!

Posted on by:

gabrielrufino profile

Gabriel Rufino

@gabrielrufino

Fullstack Developer around JavaScript stack. Solving problems, generating value!

Discussion

markdown guide
 

Perhaps worth noting is that there is a performance penalty with Array.prototype.includes. Such a "membership check" can iterate across the length of the array, especially in instances where the argument passed does not exist.

In such a scenario, it may be advisable (depending on how often this is done), to convert to a set and perform these membership checks against that. The example you used seem to be constant versus a list of values that are not yet known until runtime.

 

Wow!!! Nice.

I didn't know. Thanks for contribute

 

Ah! If you didn't, Gabriel -- it may be worth your effort in covering some basic data structures and algorithms and algorithmic complexity (in both time and space). This isn't as big a deal when operating on just the front-end (browser) with small chunks of data, but if you ever use JS (Node) on the backend, this is important and also in instances where the UI is comprised of a LOT of data in a single-page app -- think Facebook. I've seen people do multiple nesting of for-loops (in Ruby) that took down an instance of a worker which typically equates to lost earnings due to downtime

 

Actually there’s ["maintainer", "admin", "developer"].indexOf(access) > -1 as well. Include is definitely better but I don’t think anyone uses multiple || for the same variable.

 

Thanks for this amazing trick! I'll use it in my blog!