🎓 A1Learner
🔍

JavaScript Array Search

Array search methods find items inside an array. Each method answers a different question about the items.

Find a position

indexOf reports where an item sits. A missing item gives -1.

const fruits = ["Apple", "Pear", "Plum"];
console.log(fruits.indexOf("Pear"));
console.log(fruits.indexOf("Fig"));

Check membership

includes gives a plain yes or no answer. It returns a boolean value.

const fruits = ["Apple", "Pear", "Plum"];
console.log(fruits.includes("Plum"));
console.log(fruits.includes("Fig"));

Find by a test

find takes a small arrow function as its test. It returns the first item that passes.

const scores = [4, 12, 7, 19];
console.log(scores.find(score => score > 10));

Example

const prices = [8, 15, 22, 9];
console.log(prices.indexOf(22));
console.log(prices.includes(15));
console.log(prices.find(price => price > 20));

Key points

  • indexOf returns the position of the first matching item.
  • indexOf returns -1 when the item is missing.
  • includes returns true when the item is present.
  • includes returns false when the item is absent.
  • find returns the first item that passes a test.
  • findIndex returns the position of the first item that passes a test.

In this example, indexOf reports that 22 sits at position 2. includes confirms that 15 is present. find returns 22, the first price over 20.

Note

strings have search methods with the same names, taught in String Search.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does indexOf return when the item is not in the array?