VCF

Unit 5 · Data and algorithms

Why your search gives up after one item

A return inside the loop ends the whole function. Put return -1 after the loop, so it only runs once every item has been checked and none matched.

The mix-up

What people often think

“If the first card is not a match, the target is not there.”

What the tutor says

Returning -1 inside the loop stops after one card. Only return -1 after the loop has checked every item.

Where does the code go after the last card has been checked?

How it works

One item not matching proves nothing about the rest. Return early only when you find the target; the “not found” answer belongs after the loop.

Start the loop at i = 0, or the first item is never checked. And always return something when nothing is found, so the caller can tell the difference.

Side by side

The mix-upJavaScript
for (let i = 0; i < list.length; i++) {
  if (list[i] === target) return i;
  else return -1;  // gives up after one
}
Only the first item is ever checked.
What worksJavaScript
for (let i = 0; i < list.length; i++) {
  if (list[i] === target) return i;
}
return -1;  // checked them all
Not found only after the whole list.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “The target will always be in the list.”

    Searches often come up empty. After the loop, return -1 so the caller knows nothing was found.

  • “A loop over a list starts at 1.”

    Start at i = 0, or you skip the first item. That is why the check for index 0 fails.

Practise it with a tutor watching

Search

Write a linear search and explain when binary search is allowed and why it wins.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.