DEV Community

yns
yns

Posted on

How to check if a value is present in an array.

When working with arrays in JavaScript, one of the cleanest and most efficient ways to check if a value exists is by using the some() method.


✅ What is some()?

  • some() is an array method that takes a callback function.
  • It returns:
    • true if at least one element satisfies the condition.
    • false if no elements match.
  • It stops iterating as soon as a match is found (great for performance).

Example:

const arr = ['a', 'b', 'c'];
const check = arr.some(x => x === 'z');
// Output: false

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
alexmustiere profile image
Alex Mustiere

There is includes() that can also be used.
It doesn't need a predicate and is the best solution to check if a value is in an array.

const arr = ['a', 'b', 'c'];
const check = arr.includes('z');
// Output: false
Enter fullscreen mode Exit fullscreen mode