Computer Programming 1 (JavaScript) • Core Data Structures

Searching Arrays — I can search an array for a value and stop early when found at my level.

Learn how to scan through arrays efficiently by stopping the moment you find what you need.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

From the earliest days of computing, one of the most fundamental tasks a program must perform is searching — finding a specific piece of data within a collection. Before databases, search engines, or even operating systems existed, programmers needed reliable ways to locate values stored in memory. The simplest approach, scanning items one by one from start to finish, became known as linear search (also called sequential search). This technique mirrors how you might flip through a stack of papers looking for a specific page — you check each one until you find it or run out of pages.

1945 • Von Neumann Architecture

John von Neumann describes stored-program computers where data lives in sequential memory cells — the precursor to arrays.

1946 • First Sequential Searches

Early programs on ENIAC use step-by-step memory scanning to locate values, establishing linear search as the default algorithm.

1962 • Algorithm Analysis Emerges

Donald Knuth begins formalizing algorithm efficiency. Linear search is classified as O(n), meaning its time grows proportionally with data size.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript at Netscape. Arrays become a built-in data type, making search operations accessible to web developers everywhere.

2015 • ES6 Adds Modern Array Methods

JavaScript gains methods like Array.find() and Array.findIndex(), which internally implement linear search with early exit built in.

Despite decades of advances in search algorithms, linear search remains the go-to technique when your data is unsorted or when the collection is small. The key insight we'll explore in this lesson is early exit — the idea that once you find the target value, you should immediately stop searching instead of pointlessly checking every remaining element. This simple optimization can dramatically reduce wasted work.

SECTION 2

Core Principles & Definitions

Before diving into code, let's establish the foundational ideas behind searching arrays. An array is an ordered list of values stored in a single variable. Each value has a numeric position called its index, starting at 0. When we search an array, we're asking: "Does this specific value exist in the array, and if so, where?"

1

Linear Search

Check each element in order, from index 0 to the end, comparing it to the target value. This is the simplest and most intuitive search strategy.
2

Early Exit (Short-Circuit)

Stop the loop immediately when the target is found. Use a return statement inside a function or a break statement inside a loop to halt early.
3

Iteration

The process of repeating an action for every element in a collection. A for loop is the classic tool for iterating through array indices.
4

Comparison

Each iteration performs a comparison using === (strict equality) to test whether the current element matches the target. Strict equality avoids type-coercion surprises.
5

Return Value

A search function typically returns the index where the value was found, or -1 if the value doesn't exist in the array — following the same convention as JavaScript's built-in indexOf().
✦

KEY TAKEAWAY

Think of searching an array like looking for your friend in a line of people. You walk along the line, checking each face. The moment you spot your friend, you stop walking — you don't keep checking every person behind them. That's early exit. Without it, you'd pointlessly walk the entire line every single time, even if your friend was the very first person.

SECTION 3

Visual Explanation — How Linear Search Works

The diagram below shows a linear search in action. We have an array of six numbers and we're searching for the value 7. The search checks each element from left to right. Notice how it stops at index 3 the moment it finds 7, leaving indices 4 and 5 unchecked — that's the early exit in action.

Linear Search for value 7 with Early Exitindex 03index 19index 21index 37index 45index 523 ≠ 7continue9 ≠ 7continue1 ≠ 7continue7 === 7FOUND!skippedResultreturn 3 // found at index 3, checked only 4 of 6 elements✓ Checked (4 elements)Indices 0, 1, 2, 3⊘ Skipped (2 elements)Indices 4, 5
The search scans indices 0 through 3. When the value 7 is found at index 3, the function returns immediately. Indices 4 and 5 (shown dashed and faded) are never checked — that's the early exit optimization.

Without early exit, the loop would needlessly continue to index 4 and index 5 even though the answer was already found at index 3. In this small example, we saved 2 comparisons. In an array of a million elements where the target sits at index 10, early exit would save 999,990 comparisons — a massive difference.

SECTION 4

How It Works — The Code Patterns

There are two primary ways to implement early exit in JavaScript: using return inside a function and using break inside a loop. Both achieve the same goal — they halt execution the moment the target is found — but return is generally cleaner because it exits both the loop and the function in one step.

Pattern 1 — return in a Function

When your search lives inside a function, return is the cleanest early exit. The function immediately stops and sends back the index. Here is the standard pattern:

LINEAR SEARCH WITH RETURN

functionlinearSearch(arr,target)for(leti=0;i<arr.length;i++)if(arr[i]===target)returni;//←earlyexit!return−1;//notfoundfunction linearSearch(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { return i; // ← early exit! } } return -1; // not found }

arr = the array to search, target = the value to find. Returns the index of the first match, or -1 if not found.

Pattern 2 — break in a Loop

Sometimes your search isn't inside a separate function — maybe it's in the middle of other code. In that case, you can use break to exit only the loop, and store the result in a variable.

LINEAR SEARCH WITH BREAK

letfoundIndex=−1;for(leti=0;i<arr.length;i++)if(arr[i]===target)foundIndex=i;break;//←earlyexit!//foundIndexisnowtheresultlet foundIndex = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { foundIndex = i; break; // ← early exit! } } // foundIndex is now the result

The variable foundIndex starts at −1 (meaning "not found"). If the target is located, the variable is updated and break halts the loop.

The Wrong Way — No Early Exit

⚠

Common Mistake

A frequent beginner error is writing a loop that checks every element and only records the answer but never stops. For example, using forEach has no way to break out early — it always runs through the entire array. This wastes time and can introduce bugs if the target appears more than once and you accidentally overwrite the result.

SECTION 5

Efficiency — Best, Worst, and Average Cases

How efficient is linear search? That depends on where the target value sits in the array. Computer scientists describe algorithm efficiency using Big O notation, which describes how the number of operations grows as the input size (n) increases. For linear search, we consider three scenarios.

Linear Search — Comparisons vs. Array SizeArray size (n)Comparisons020406080100020406080100Worst O(n)Avg O(n/2)Best O(1)● Best case: O(1)Target is the first element● Average case: O(n/2)Target is near the middle● Worst case: O(n)
This graph plots the number of comparisons against array size for three scenarios. The best case (green) is a flat line at 1 comparison. The average case (amber) grows at half the rate. The worst case (red) grows linearly — hence the name linear search.
ScenarioWhen it happensComparisonsBig O
Best caseTarget is at index 01O(1)
Average caseTarget is roughly in the middlen / 2O(n)
Worst caseTarget is last or not in arraynO(n)

Efficiency breakdown for linear search on an array of n elements

Even though the average case is technically n/2, Big O notation drops constants, so both the average and worst cases are written as O(n). The key point is that early exit makes the best and average cases significantly better than the worst case. Without early exit, every search would always be the worst case — O(n) every time.

SECTION 6

Worked Example — Finding a Student's Name

Let's trace through a complete example. We have an array of student names and want to find the index of "Maria". We'll write the function, then step through each iteration.

Search for "Maria" in a Names Array

  1. 1

    Step 1 — Define the array and target

    We start with let names = ["Alex", "Jordan", "Maria", "Sam", "Taylor"]; and our target is "Maria". The array has 5 elements (indices 0 through 4).
    Array length: 5
  2. 2

    Step 2 — Iteration i = 0

    Compare names[0] which is "Alex" to our target "Maria". They are not equal ("Alex" !== "Maria"), so the loop continues to the next iteration.
    No match → continue
  3. 3

    Step 3 — Iteration i = 1

    Compare names[1] which is "Jordan" to "Maria". Still no match, so we continue.
    No match → continue
  4. 4

    Step 4 — Iteration i = 2 (MATCH!)

    Compare names[2] which is "Maria" to "Maria". They match! The if condition is true, so we immediately execute return 2. The function exits right now — indices 3 and 4 are never checked.
    return 2 — found at index 2 after only 3 comparisons
  5. 5

    Step 5 — Verify the result

    Calling linearSearch(names, "Maria") returns 2. We made 3 comparisons out of a possible 5. Without early exit, we would have checked all 5 elements every time, wasting 2 comparisons. The savings grow dramatically with larger arrays.
    Saved 40% of comparisons thanks to early exit

SECTION 7

Comparing Search Approaches

JavaScript gives you several ways to search arrays. Some have early exit built in, some don't, and some require sorted data. Let's compare them so you know which tool to reach for.

ApproachEarly Exit?ReturnsRequires Sorted?Notes
for loop + return✅ YesIndex or −1NoFull control; the approach taught in this lesson
for loop + break✅ YesVariable you setNoUse when not inside a function
indexOf()✅ Yes (built-in)Index or −1NoBuilt-in method; uses linear search internally
find()✅ Yes (built-in)Element or undefinedNoReturns the value itself, not the index
includes()✅ Yes (built-in)true / falseNoOnly tells you if it exists, not where
forEach()❌ NoundefinedNoCannot break or return early — always runs fully

Comparison of array search approaches in JavaScript

✦

KEY TAKEAWAY

JavaScript's built-in methods like indexOf() and find() already use early exit internally. Writing your own for loop with return teaches you exactly what those methods do under the hood. It's like learning to change a tire before relying on roadside assistance — you understand the mechanism even when you use the convenient shortcut.

SECTION 8

Connection to Binary Search & Advanced Topics

Linear search is simple and works on any array, but it has a limitation: for very large datasets, checking every element until you find the target can be slow. When the array is sorted, a much faster algorithm called binary search becomes available. Binary search repeatedly cuts the search space in half, achieving O(log n) performance — dramatically faster for large arrays.

FeatureLinear SearchBinary Search
Array must be sorted?NoYes
Worst-case timeO(n)O(log n)
Comparisons for 1,000,000 elementsUp to 1,000,000At most 20
Implementation complexityVery simpleModerate (tricky edge cases)
Best forSmall or unsorted arraysLarge, sorted arrays

Linear search vs. binary search

Understanding linear search with early exit is an essential stepping stone. You'll encounter binary search in a later unit, and the concept of stopping as soon as you have your answer applies there too. Beyond searching, the early exit pattern appears everywhere in programming: validating user input, checking conditions before running expensive operations, and short-circuit evaluation in boolean expressions (&& and ||). Mastering it now will pay dividends throughout your programming career.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why using return inside a for loop to exit early is more efficient than letting the loop run through every element. What would happen if the target is at index 0 in a 10,000-element array and you don't use early exit?
Show answer
Using return stops the function immediately when the target is found, so no additional comparisons are made. Without early exit, the loop would check all 10,000 elements even though the answer was found at the very first index. That means 9,999 unnecessary comparisons. Early exit transforms the best case from O(n) to O(1) — a single comparison — and improves the average case by roughly half.

Question 2: BASIC CALCULATION

Given the array [10, 20, 30, 40, 50], trace through a linear search for the value 30. How many comparisons are made before the function returns? What value does it return?
Show answer
The search starts at index 0: 10 ≠ 30, move on. Index 1: 20 ≠ 30, move on. Index 2: 30 === 30, match found! The function executes return 2. A total of 3 comparisons are made. The elements at indices 3 and 4 (40 and 50) are never checked because the early exit via return stops the loop immediately upon finding the match.

Question 3: INTERMEDIATE

Write a function called findFirst that takes an array of strings and a target string. It should return the index of the first occurrence, or -1 if not found. Then explain: if the array is ["cat", "dog", "cat", "bird"] and the target is "cat", what does your function return and why doesn't it return index 2?
Show answer
The function should be: function findFirst(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { return i; } } return -1; } When searching for "cat", the loop checks index 0 first: "cat" === "cat" is true, so it immediately returns 0. It never reaches index 2 because the early exit via return fires on the first match. This is exactly why the function returns the first occurrence — the loop processes elements in order and stops at the earliest match.

Question 4: APPLIED

A teacher stores 200 student IDs in an array. She wants a function that checks whether a given ID is in the array and returns true or false. Write the function using a for loop with early exit. Then explain: if the IDs are unsorted, what is the maximum number of comparisons? If the IDs were sorted, would a different algorithm be better?
Show answer
The function: function hasStudent(ids, targetId) { for (let i = 0; i < ids.length; i++) { if (ids[i] === targetId) { return true; } } return false; } In the worst case (ID not found or at the very end), all 200 elements must be checked — 200 comparisons. On average, if the ID exists, you'd check about 100 elements. If the IDs were sorted, binary search could find the answer in at most about 8 comparisons (log₂(200) ≈ 7.6), which is dramatically faster. For 200 elements, linear search is still acceptably fast, but for thousands of students, sorting and using binary search would be worth the effort.

Question 5: CRITICAL THINKING

Consider this code: function search(arr, target) { let result = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { result = i; } } return result; } This works but has two problems. First, identify the efficiency issue. Second, explain what happens when the target appears multiple times — does this function return the first or last occurrence, and how would you fix it to return the first occurrence efficiently?
Show answer
The efficiency issue is that there is no early exit. The loop always runs through every element regardless of whether the target was found early. The second problem is subtler: if the target appears multiple times, result keeps getting overwritten, so the function returns the LAST occurrence, not the first. To fix both problems, add a break immediately after result = i;, or better yet, refactor the function to use return i; directly instead of storing in a variable. This simultaneously adds early exit (efficiency) and ensures only the first occurrence is returned (correctness).

SUMMARY

Summary — Searching Arrays with Early Exit

Summary

Linear search is the foundational algorithm for finding a value in an array. It works by iterating from index 0 to the end, comparing each element to the target value using strict equality (===). The critical optimization is early exit — using return (inside a function) or break (inside a standalone loop) to stop the moment the target is found. This reduces the best case to O(1) and the average case to roughly n/2 comparisons.

A well-written search function returns the index where the value was found, or -1 if it doesn't exist. Avoid forEach for searching because it cannot exit early. JavaScript provides built-in methods like indexOf(), find(), and includes() that implement early-exit search internally. Understanding how to write your own linear search prepares you for more advanced algorithms like binary search and deepens your understanding of how loops, conditions, and control flow work together.

Varsity Tutors • Computer Programming 1 (JavaScript) • Searching Arrays — I can search an array for a value and stop early when found at my level.