Find the first match using linear search
Quick answer
Linear search inspects elements one at a time and can stop at the first match. It works without sorted input, making it useful for small or unsorted collections.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function findFirst(values, target) { for (let i = 0; i < values.length; i++) { if (values[i] === target) return i; } return -1;}console.log(findFirst([8, 3, 8], 8), findFirst([8, 3], 9));Expected console output:
0 -1The first 8 occurs at zero; the absent 9 returns -1.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const products = [{id:"B", stock:0}, {id:"A", stock:3}];const index = products.findIndex(p => p.stock > 0);console.log(index, products[index].id);Expected console output:
1 AThe predicate rejects zero and accepts the second record.
How it works and cost model
For a dense array of finite numbers, iterate from index 0 to length - 1, compare with strict equality and return the first matching index or -1. This costs at most n comparisons, with O(1) auxiliary storage. A match at index 0 is valid; duplicate values do not change the first-match contract. For a predicate or special values such as NaN, choose equality semantics explicitly. Use findIndex when its callback semantics suit the task.
Common mistakes
Do not test the returned index as a Boolean: zero is falsy and -1 is truthy. Compare with -1 explicitly.
Practice
Write a first-match search for an array of stock codes; test a duplicate, a match at index zero, an empty array and an absent code.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Find the first match using linear search — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Which input precondition is unnecessary for ordinary linear search?
What is the worst-case number of equality comparisons on n dense items?
Which test correctly detects an index returned by this first-match algorithm?
What is the exact console output in the Linear search example 1?
function findFirst(values, target) { for (let i = 0; i < values.length; i++) { if (values[i] === target) return i; } return -1;}console.log(findFirst([8, 3, 8], 8), findFirst([8, 3], 9));What is the exact console output in the Linear search example 2?
const products = [{id:"B", stock:0}, {id:"A", stock:3}];const index = products.findIndex(p => p.stock > 0);console.log(index, products[index].id);