Earlier this week I wrote about how the JavaScript includes() method works on a string. It works a bit differently on an array, and I wanted to go into that.

When processing it on a string, the includes() method performs a partial match. If the argument string exists in the source, true is returned. Otherwise false is returned.

However, when using includes() on an array, an exact match is required. Not a match to the array, but a match between the object to search for and an item inside the array.

You can use includes() on an array to search through an item in that array. Let's start with a variable that's an array:

view plain print about
1let myArray = ['The', 'Quick', 'Brown', 'Fox', 'Jumped', 'Over', 'The', 'Lazy', 'Dogs'];

Now we can use includes to search for for items in that array

view plain print about
1console.log(myArray.includes('Fox')); // returns true

This will output a true since the string Fox is an element in the array.

We can try a full string comparison:

view plain print about
1console.log(myArray.includes('The Quick Brown Fox Jumped Over The Lazy Dogs'));

This will return false, because even though each work in the string is part of the array, the full string is not a full element on the array.

What happens if you search for something not in the original string? Techincally we did that above, but here is a check with a new word not in the original array.

view plain print about

The value will return false.

Play with a Plunker here.

I think I'm gonna be back next week to do some testing with an object full of arrays.