Introduction
In JavaScript, we may need to check if an array includes a value.
In this article, we'll show how to verify if an array contains a specific value.
How to check if an array includes a value in JavaScript
To check if an array includes a value in modern browsers we can use array.includes(...)
method:
const array = ['one', 'two', 'three'];
console.log(array.includes('one')); //true
console.log(array.includes('four')); //false
The array.includes(...)
method returns true if an array contains a specific value, or false otherwise.
In older browsers we can use indexOf()
function:
var array = ['one', 'two', 'three'];
console.log(array.indexOf('one') >= 0); //true
console.log(array.indexOf('four') >= 0); //false
If array.indexOf(...)
returns value greaten then 0 it means array includes specific value.
Conclusion
To check if an array includes a value in JS we can use the array.includes(...)
method available in modern browsers or array.indexOf(...)
available in older browsers.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}