Array Search and Test in JavaScript

Introduction

Programs constantly ask: Does this list include X? Where is it? Which items match a rule? This chapter covers includes, indexOf, find, findIndex, and some / every—core tools before higher-order methods like filter.

Prerequisites

includes — Membership Test

javascript
// Check presence (uses ===)
const roles = ["admin", "editor", "viewer"];
 
console.log(roles.includes("editor"));
console.log(roles.includes("owner"));

Works well for primitives; objects compare by reference.

indexOf / lastIndexOf

javascript
// First index or -1 if missing
const ids = [10, 20, 20, 30];
 
console.log(ids.indexOf(20));
console.log(ids.lastIndexOf(20));
console.log(ids.indexOf(99));

find — First Matching Element

javascript
// Return first object where predicate true
const users = [
  { id: 1, name: "Ada", active: true },
  { id: 2, name: "Lin", active: false },
];
 
const activeUser = users.find((user) => user.active);
console.log(activeUser?.name);

Returns undefined if none match.

findIndex — Index of Match

javascript
// Index for update/remove
const index = users.findIndex((user) => user.id === 2);
console.log(index);
 
if (index !== -1) {
  users[index].active = true;
}
console.log(users);

some and every

javascript
// any / all tests
const scores = [70, 82, 91, 88];
 
const anyPass = scores.some((s) => s >= 90);
const allPass = scores.every((s) => s >= 60);
 
console.log(anyPass, allPass);

filter Preview

Returns all matches as a new array (detailed in higher-order methods):

javascript
// All passing scores
const passing = scores.filter((s) => s >= 80);
console.log(passing);

Mini Example: Find Product by SKU

javascript
// Catalog lookup
const catalog = [
  { sku: "A1", title: "Pen", price: 2 },
  { sku: "B2", title: "Mug", price: 12 },
];
 
function findBySku(sku) {
  return catalog.find((item) => item.sku === sku);
}
 
console.log(findBySku("B2"));
console.log(findBySku("Z9") ?? "Not found");

FAQ

includes vs indexOf !== -1?

Prefer includes for readability when you only need yes/no.

Do these methods work on strings?

Strings have their own methods (includes, indexOf)—similar ideas, different type.

Can find return multiple items?

No—use filter for multiple matches.

What comes next?

Slice and splice patterns.