How to check if an array contains a specific value in javascript


Is there any method to check directly if an array contains a specific value instead of iterating array for comparing value with every element present in the array?

1 Answer

5 years ago by

You don't need to iterate over the array elements to check if the array has a specific value. Modern javascript provides couple of ways to check if a value is present in an array.

1. includes()

ES6 introduced this function, and it will result either true or false. You can also specify an optional second parameter like shown below which specifies the position to start the search.

let arr = ['foo', 'bar', 'mark'];

console.log(arr.includes('bar'));
console.log(arr.includes('bar',1)); // optional second parameter specifies the position to start the search.

2. indexOf()

This function also used to check if a value is present in the given array and it will result either -1(no match) or a positive index of the value you are searching for.

let arr = ['foo', 'bar', 'mark'];

if(arr.indexOf('mark')>-1){
  console.log('value is present in the array');
} else {
  console.log('value is not present in the array');
} 
5 years ago by Divya