Prior to the ES6 release, checking if an item existed in an array was not an easy task. For example, if I had an array called customers
, that contained names of our customers, and I wanted to verify if Sam exists, I’d have to do something like this:
var customers = ["Olly", "Rex", "Sam", "Praise"]function itemExists(item, container) {// traverse the containerfor (let i = 0; i < container.length; i++) {if (container[i] == item) {console.log(true);}}}// call itemExists functionitemExists("Sam", customers);// true
It works. However, the issue with this method is that it is long and also non-performant.
Array.includes
is a helper and is preferable to the previous method. For example, we can use customers.includes
to achieve the same task as the previous block:
var customers = ["Olly", "Rex", "Sam", "Praise"];console.log(customers.includes("Sam"));// true
This is more performant and readable and it works on all modern browsers except IE. For more information, see the official documentation for Array.includes.