Sub topic 11
Finding Elements and Testing Conditions
This chapter assumes you know arrow functions, strict equality (===), and the callback signature (element, index, array) from the earlier chapter on callbacks. You should also be able to run snippets in Node.js or a browser console.
Searching is one of the most common things you do with an array. JavaScript gives you several methods for it, and each one answers a slightly different question:
- Which element matches? Use
findorfindLast. - Where is the matching element? Use
findIndex,findLastIndex,indexOf, orlastIndexOf. - Is this value present? Use
includes. - Does any element match? Use
some. - Do all elements match? Use
every.
None of these methods mutate the array. The usual bug is picking a method whose return value doesn't fit the question, or forgetting how it compares values.
The Two Families: Predicate vs Value Search
Search methods come in two kinds.
Predicate methods take a callback that returns true or false. A predicate is a function that tests one element. find, findIndex, findLast, findLastIndex, some, and every all work this way, so they can test any condition, such as a property value or a range.
Value methods take a value and compare each element to it. indexOf, lastIndexOf, and includes work this way. They are shorter to write, but they can only check for equality.
const users = [
{ name: 'Ana', age: 31 },
{ name: 'Ben', age: 17 },
{ name: 'Cleo', age: 24 }
];
console.log(users.find(u => u.age < 18)); // { name: 'Ben', age: 17 }
console.log(users.findIndex(u => u.name === 'Cleo')); // 2
console.log(users.some(u => u.age < 18)); // true
console.log(users.every(u => u.age > 10)); // true
console.log([1, 2, 3].includes(2)); // trueThe table lists what each method returns.
| Method | Argument | Returns on match | Returns on no match |
|---|---|---|---|
| `find` | predicate | first matching element | `undefined` |
| `findLast` | predicate | last matching element | `undefined` |
| `findIndex` | predicate | first matching index | `-1` |
| `findLastIndex` | predicate | last matching index | `-1` |
| `indexOf` | value, optional `fromIndex` | first matching index | `-1` |
| `lastIndexOf` | value, optional `fromIndex` | last matching index | `-1` |
| `includes` | value, optional `fromIndex` | `true` | `false` |
| `some` | predicate | `true` | `false` |
| `every` | predicate | `true` if all match | `false` |
find and findLast
find walks the array from index 0 and returns the first element for which the predicate returns a truthy value. findLast, added in ES2023, walks from the end. Both stop as soon as they find a match.
const logs = [
{ level: 'info', msg: 'start' },
{ level: 'error', msg: 'disk full' },
{ level: 'info', msg: 'retry' },
{ level: 'error', msg: 'timeout' }
];
console.log(logs.find(l => l.level === 'error').msg); // 'disk full'
console.log(logs.findLast(l => l.level === 'error').msg); // 'timeout'find returns the element itself, not a copy. If the element is an object, changing it through the returned reference also changes the object inside the array.
const items = [{ id: 1, qty: 2 }, { id: 2, qty: 5 }];
const item = items.find(i => i.id === 2);
item.qty = 0;
console.log(items[1].qty); // 0The undefined ambiguity
find returns undefined when nothing matches. That result is ambiguous when the array can actually contain undefined:
const values = [undefined, 3];
console.log(values.find(v => v === undefined)); // undefined (found it)
console.log(values.find(v => v === 99)); // undefined (not found)If you need to know whether a match exists, call findIndex and compare the result to -1, or call some.
Accessing a property on a missing result is the most common bug:
const people = [{ name: 'Ana' }];
const match = people.find(p => p.name === 'Zed');
console.log(match?.name ?? 'not found'); // 'not found'Without the optional chaining (?.), match.name throws a TypeError.
findIndex and findLastIndex
These two methods work like find and findLast, but they return the position of the match, or -1 if there isn't one. Use them when you plan to replace or remove the element.
const tasks = ['write', 'test', 'deploy'];
const i = tasks.findIndex(t => t === 'test');
if (i !== -1) {
tasks.splice(i, 1);
}
console.log(tasks); // ['write', 'deploy']indexOf, lastIndexOf, and includes
The value methods compare elements to the value you pass. indexOf and lastIndexOf use strict equality (===). includes uses the SameValueZero algorithm. The two differ in one case: NaN.
const data = [1, NaN, 3];
console.log(data.indexOf(NaN)); // -1 (NaN !== NaN)
console.log(data.includes(NaN)); // true
console.log([-0].includes(0)); // true (both treat -0 and 0 as equal)Both methods compare objects by reference. Two objects with the same contents are still different objects:
const list = [{ id: 1 }];
console.log(list.includes({ id: 1 })); // false
console.log(list.some(o => o.id === 1)); // trueWhen you search for objects by their contents, use a predicate method.
The fromIndex argument
All three value methods take an optional second argument that sets where the search starts. A negative value counts back from the end.
const letters = ['a', 'b', 'a', 'c', 'a'];
console.log(letters.indexOf('a', 1)); // 2
console.log(letters.indexOf('a', -2)); // 4
console.log(letters.lastIndexOf('a', 3)); // 2 (searches backward from index 3)
console.log(letters.includes('b', 2)); // falseYou can collect every position of a value by calling indexOf in a loop:
function allIndexes(arr, value) {
const result = [];
let i = arr.indexOf(value);
while (i !== -1) {
result.push(i);
i = arr.indexOf(value, i + 1);
}
return result;
}
console.log(allIndexes(['a', 'b', 'a', 'c', 'a'], 'a')); // [0, 2, 4]some and every
some returns true as soon as one element passes the predicate. every returns false as soon as one element fails it. Because both stop early, they cost less than filter(...).length > 0 when the answer shows up early in the array.
const scores = [72, 88, 45, 91];
let calls = 0;
const anyFailing = scores.some(s => { calls++; return s < 50; });
console.log(anyFailing, calls); // true 3
console.log(scores.every(s => s >= 40)); // trueEmpty arrays: vacuous truth
On an empty array, every returns true and some returns false. This is consistent with logic: no element fails, and no element passes. It can surprise you in validation code, though:
const cart = [];
console.log(cart.every(item => item.inStock)); // true
console.log(cart.some(item => item.inStock)); // falseIf an empty cart should not count as "all in stock", check the length explicitly: cart.length > 0 && cart.every(...).
some and every mirror each other. arr.every(fn) always gives the same result as !arr.some(x => !fn(x)).
Sparse Arrays and Holes
A sparse array has empty slots, or holes, where no element exists. The search methods handle holes differently:
const sparse = [1, , 3];
console.log(sparse.indexOf(undefined)); // -1 (holes skipped)
console.log(sparse.includes(undefined)); // true (holes read as undefined)
console.log(sparse.findIndex(x => x === undefined)); // 1 (holes visited)
console.log(sparse.some(x => x === undefined)); // false (holes skipped)find, findIndex, findLast, findLastIndex, and includes read holes as undefined. indexOf, lastIndexOf, some, and every skip them. The Edge Cases chapter covers sparse arrays in more detail. In practice, avoid creating holes at all.
Performance Notes
Every method here performs a linear scan, so the time it takes grows with the array's length. Calling includes inside a loop over another array gives quadratic time. For repeated membership checks, build a Set once:
const allowed = ['read', 'write', 'admin'];
const allowedSet = new Set(allowed);
const requested = ['read', 'delete', 'write'];
console.log(requested.filter(p => !allowedSet.has(p))); // ['delete']Set.prototype.has also uses SameValueZero, so it handles NaN the same way includes does.
Exercise
Given const nums = [4, NaN, 8];, what do nums.indexOf(NaN), nums.includes(NaN), and nums.findIndex(Number.isNaN) return, and why?
Show answer
-1, true, and 1. indexOf uses strict equality, and NaN === NaN is false. includes uses SameValueZero, which treats NaN as equal to itself. findIndex calls the predicate Number.isNaN on each element, and that returns true at index 1.
Exercise
A function validates an order with return order.items.every(i => i.price > 0);. Why does it accept an order with no items, and how would you fix it?
Show answer
every returns true on an empty array because no element fails the predicate. Fix it by checking the length first: return order.items.length > 0 && order.items.every(i => i.price > 0);.
Exercise
Write an expression that returns the name of the most recent user younger than 18 in users, or the string 'none' if there isn't one.
Show answer
users.findLast(u => u.age < 18)?.name ?? 'none'. findLast searches from the end, optional chaining avoids a TypeError when nothing matches, and ?? supplies the fallback.