How to Check If a Value Exists in an Array in JavaScript
To check if a particular value exists in an array in JavaScript we can use the built-in indexOf()
and includes()
methods with some logic to do something depending on the result.
Using indexOf()
indexOf()
takes the element value to look for inside the ()
(parenthesis) of the method. It returns -1
for no matches and the index of the array element if found.
var fruit = ['Apple', 'Orange', 'Strawberry', 'Peach'];
var match = fruit.indexOf('Peach');
if (match !== -1) {
console.log('Match found on index '+ match);
} else {
console.log('Do something different...');
}
Match found on index 3
Using includes()
includes()
returns true
if the array contains a specified value and false
if not.
var fruit = ['Apple', 'Orange', 'Strawberry', 'Peach'];
if (fruit.includes('Peach')) {
console.log('Do something...');
} else {
console.log('Do something different...');
}
Do something...
Conclusion
You now know two different ways to check for the presence of a value in an array in JavaScript. If you only need to know if it is there use includes()
and if you need its index use indexOf()
.
array