Earlier this week I wrote about how the JavaScript includes() method works on a string. I followed it up on a post about how includes() works on an array.

The short summary is that for strings we're looking for a partial match of the target string to exist in the source string. For an array, we are looking for an exact match between the target string and a single element within the source array.

After writing the post about searching a string array, I wanted to explore a bit about object arrays. On paper, object arrays work exactly string arrays do, however the comparison can be a bit confusing to newcomers to JavaScript.

Let's start with an array of objects:

view plain print about
1let myArrayWithObjects = [
2 { word: 'The'},
3 { word:'Quick'},
4 { word:'Brown'},
5 { word: 'Fox'},
6 { word: 'Jumped'},
7 { word: 'Over'},
8 { word: 'The'},
9 { word: 'Lazy'},
10 { word: 'Dogs'}
11 ];

Each object contains a single property, `word`.

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

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

This will output a false response, since no strings exist in the array; only objects. That is what we'd expect.

Let's create a new object variable:

view plain print about
1let compareObject1 = { word: 'Fox'};

From our perspective, as a human reviewing code it looks like this object is equal to an object within the array. What happens if we perform the includes()?

view plain print about

Try it, and you'll see that the response if also false How come? Because even though the two objects look similar they are two independent objects. JavaScript performs this compare by looking at the object's space in memory and these two objects that look similar occupy different places in memory.

If we set our source string to a real value insdie the array and use that to compare, we should get a true result:

view plain print about

This is because the the target value is pointed at the same object instance that resides inside the array. The comparison is true.

Play with a Plunker here.

Every once in a while I have a developer conversations and go on a weird tangent, writing a bunch of blog posts to drill into something that should be simple and intuitive. I think this is one of those times, but I'm always happy to explore and share those explorations.