Anjan Dutta
Check if an array includes a value in Javascript
Check if an array includes a value in Javascript
Updated On: 19/09/2021
Today I am going to explain how to check if an array contains a value in Javascript.
Check if array includes a value in Javascript
ES6 has introduced the new array function includes() that can perform our intended operation.
The includes()
method works on an array. It takes one parameter, the item that we want to find in an array.
See the below code for your reference.
var students = ['john', 'jane', 'jim'];
console.log(students.includes('jane')); // true
Simple, isn’t it? But, this method doesn’t work in older browsers. For example, in IE, the includes()
method will not work.
So we need to use a workaround for older browsers.
The indexOf() method for older browser version
Using indexOf()
method, we can determine if an element is present in an array or not. Similar to the includes()
method the indexOf()
method also works on arrays and, it takes one argument.
See the code below.
var students = ['john', 'jane', 'jim'];
console.log( students.indexOf('jane') > -1 ); // true
Even though the indexOf()
method supports both old and new browsers, it has a few drawbacks.
For example, if an array has NaN
or undefined
in it and we try to find out then, indexOf()
will not give us the correct answer.
See the below code for details.
Check for NaN index
The includes()
method gives us the correct result, whereas the indexOf()
couldn’t detect NaN
.
var students = ['john', NaN, 'jane', 'jim'];
console.log(students.includes(NaN)); // true
console.log(students.indexOf(NaN) > -1); // false
Check for Undefined index
The includes()
method gives us the correct result, whereas the indexOf()
couldn’t detect undefined
.
var students = ['john', , 'jane', 'jim'];
console.log(students.includes(undefined)); // true
console.log(students.indexOf(undefined) > -1); // false
So, to handle more detailed scenarios like this, we have to implement more workarounds for older browsers to check if array includes a value in Javascript.
Thanks for reading.