DevPath · Learn to code ESPTEN

Arrays and their methods

Searching for elements

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
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Adding, removing and slicingFunctional methods: map, filter, reduce and more →