We often want to check if an array includes a specific item. It's been common to do this with the Array.prototype.indexOf
method, but now we have a simpler way: We can use the Array.prototype.includes
method, which is available starting with ES2016.
[00:00] To get started, open the node REPL and create an array with a bunch of numbers. Let's say you need to find out if this array contains the value 16. The traditional approach is to call the indexOf method with a given item. IndexOf will return either the items index, or -1 if the array does not contain the item.
[00:18] Now, compare the return value to -1. The result will be true for all items in the array and false otherwise. A better approach is to use the includes method, which was standardized in ES 2016. It determines whether an array includes a certain element and returns true or false as appropriate.
[00:36] The includes method accepts an optional second parameter called from index. It specifies the array position at which to start the search.
[00:43] Go ahead and search the value 16 starting at the index four. The return value will be true, because 16 is exactly at index four. If you change the four to a five, the return value will be false.
[00:55] Specify a negative value to come from the end of the array. 16 is one of the last three items, but it's not one of the last two.
[01:05] Now, create an array of numbers that includes the special not a number value or NaN. Call the index of method and try to find NaN. It will return -1. This is because NaN is not considered to be equal to itself, index of does not find it in the array.
[01:23] The includes method fixes that behavior and correctly returns true, even for NaN. Finally, notice how the includes method helps with readability. It almost looks like a regular English sentence.