An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
July 19, 2020 02:08 am GMT
Using
Using
Works with
Original Link: https://dev.to/gabrielrufino/more-readable-conditional-with-array-includes-2m3j
More readable conditional with Array.includes()
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) // truenumbers.includes(6) // falsestrings.includes('Rufino') // truestrings.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!
Original Link: https://dev.to/gabrielrufino/more-readable-conditional-with-array-includes-2m3j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To