javascript

Check if an array includes a value in Javascript

It’s another useful article on javascript arrays. Today I am going to explain how to find out if an array includes a value in Javascript.

In one of my other blog post, I have described how to perform delete operation in array. Don’t forget to check it out.

Method to check if array includes a value in Javascript

ES6 has introduced the new array function includes() that can perform our intended operation.

The includes() function 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

Using indexOf(), 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 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

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

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 till here. Please subscribe below if you like my blog.

Leave a Comment

− two = four