1. What is this?
Search answers 'where is X?' A function takes the array and the target, walks each index, and returns the index when found — or -1 when absent. Returning -1 (instead of 0) matters because 0 is a valid index. Early return stops the moment we find it.
2. Why do we use it?
Login lookups, find-in-page, inventories — search underlies them all. Linear search is the baseline every faster method beats.
3. Syntax breakdown
function find(arr, target) {Declares search with parameters array and target.
for (let i = 0; i < arr.length; i++) {Walks every valid index.
if (arr[i] === target) return i;
=== compares strictly. return hands back the index immediately.
5. Common mistakes
- Returning 0 or false for 'not found' — 0 is a valid index; use -1.
- Using = instead of === in the comparison.
- Forgetting return -1 after the loop, so absence gives undefined.
Practice task
Find "Liam" in ["Ava", "Liam", "Mia"] and log the index. Then search for "Noah" (expect -1).
Hint
console.log(find(["Ava","Liam","Mia"], "Liam")); then with "Noah".
Try it below — tests run automatically when you press Run.
Output
Press Run to see output.
Mini quiz
3 questions. Answer, then check.
1. What does linear search return when absent?
2. Why return early when found?
3. What is its Big-O?