Technical skill practice

JavaScript findIndex: Locate the First Record Matching a Condition

Use findIndex when the match is a condition on each element. It returns the first matching index or −1. Test that result explicitly before using it as a position.

The task

Locate the first available camera record and then search for an unavailable category. Compare the predicate search with indexOf on a newly constructed object.

Runnable Node 22 example

const assert = require('node:assert/strict');

const equipment = [{kind: 'camera', available: true}, {kind: 'tripod', available: true}, {kind: 'camera', available: true}];
const first = equipment.findIndex(item => item.kind === 'camera' && item.available);
assert.equal(first, 0);
assert.equal(equipment.findIndex(item => item.kind === 'microphone'), -1);
assert.equal(equipment.indexOf({kind: 'camera', available: true}), -1);
assert.equal(equipment[first], equipment[0]);
console.log(`first=${first}; kind=${equipment[first].kind}`);

Expected output and explanation

Two cameras satisfy the condition, but findIndex stops at the first and returns zero. The missing microphone produces −1. A truthiness test would mishandle both values, so compare against −1 before reading equipment[index].

The indexOf call does not inspect the new object’s fields for equality; it searches for that exact reference and fails. findIndex makes the record-level match rule explicit without changing array membership or cloning the matching item.

Output from the example

first=0; kind=camera

Pitfall to check

If you need every matching record, filter expresses a different task. If you only need the first matching value, find avoids a separate lookup. Choose the result shape the caller actually needs.

Questions, answered

Does findIndex return the matching object?

No. It returns a numeric position. find returns a value, while findIndex is useful when a later operation needs the position.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.