Trusted answers to developer questions

Easy way to check if an item exists in array in JS

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 container
for (let i = 0; i < container.length; i++) {
if (container[i] == item) {
console.log(true);
}
}
}
// call itemExists function
itemExists("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.

RELATED TAGS

es6
javascript
includes
Did you find this helpful?