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

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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources