Searching within an array
includes: is it there or not?
Returns true or false:
const animals = ["dog", "cat", "parrot"];
console.log(animals.includes("cat")); // true
console.log(animals.includes("fish")); // false
indexOf: at which position?
Returns the index of the first match, or -1 if it doesn't exist:
console.log(animals.indexOf("parrot")); // 2
console.log(animals.indexOf("fish")); // -1
A very common pattern to check for existence is:
if (animals.indexOf("cat") !== -1) {
console.log("It's there!");
}
Although these days includes is more readable for that specific question.
Examples
Checking membership
const guests = ["Ana", "Luis", "Sara"];
console.log(guests.includes("Luis")); // true
console.log(guests.indexOf("Sara")); // 2
console.log(guests.indexOf("Pepe")); // -1