DEV Community

Gabriel Rufino
Gabriel Rufino

Posted on • Edited on

3 1

Condicional mais legível com Array.includes()

Você conhece a função Array.includes() do javascript? Essa função foi especificada no ES7 e é capaz de tornar uma condicional bem mais legível.

Essa função determina se um parâmetro está contido no 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
Enter fullscreen mode Exit fullscreen mode

Conhecendo essa função, agora você pode escrever condicionais que comparam uma variável com muitas possibilidades mais legíveis trocando o or pelo Array.includes() usando a variável como parâmetro. Veja o exemplo:

Usando o operador or

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 })
  }
}
Enter fullscreen mode Exit fullscreen mode

Usando 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 })
  }
}
Enter fullscreen mode Exit fullscreen mode

Funciona com NaN

NaN === NaN // false
[1, 2, 3, NaN].includes(NaN) // true
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay