How to check if an array contains a value in JavaScript
Checking whether an array contains a specific value is fundamental for validation, conditional logic, and user interface states in modern JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented this check thousands of times in components like permission systems, feature toggles, and form validation where specific values determine application behavior.
From my extensive expertise, the most modern and efficient solution is using the ES6 includes()
method, which provides a clean boolean return value.
This approach is readable, performant, and specifically designed for membership testing.
Use the includes()
method to check if an array contains a specific value.
const fruits = ['apple', 'banana', 'orange']
const hasApple = fruits.includes('apple')
// Result: true
The includes()
method searches through the array and returns true
if the specified value is found, or false
if it’s not. In this example, fruits.includes('apple')
returns true
because ‘apple’ exists in the array. The method uses strict equality (===) for comparison, so it works reliably with primitive values like strings, numbers, and booleans. For case-insensitive string searches, convert both the array and search value to the same case first.
Best Practice Note:
This is the same approach we use in CoreUI components for permission checks and feature detection.
For object arrays, use some()
with a custom comparison: users.some(user => user.id === targetId)
. The includes()
method is supported in all modern browsers and provides better readability than alternatives like indexOf() !== -1
.