Skip to the content

Linear search

JavaScript · Unit 22: Searching and sorting

Searching an array means asking one element at a time until you hit what you want. The moment it matches, you return the position and you're out.

If the loop ends with no match, it wasn't there: you return -1, the same signal indexOf uses.

function search(nums, v) {
  const n = nums.length;
  for (let i = 0; i < n; i++) {
    if (nums[i] === v) {
      return i;
    }
  }
  return -1;
}
console.log(search([4, 8, 5], 8));

Prints

1

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    The same array gets searched twice. What does it print?

  2. 2. Complete the code

    Complete it so the function tells you which position the 8 is at.

  3. 3. Multiple choice

    What does this function do?

  4. 4. Predict the output

    steps counts the comparisons of each search. What does it print?

  5. 5. Find the bug

    search should give the position of the first fig, which is 0. Which line has the error?

  6. 6. Complete the code

    Complete it to find where in the line the person with id 4 is standing.

  7. 7. Put the lines in order

    Put search in order: it returns the position of v, or -1 if it isn't there.

  8. 8. Find the case that fails

    position(nums, v) returns the position where v first shows up, or -1 if it isn't there. Which call does it fail on?

  9. 9. Predict the output

    The walk looks for the highest score. What does it print?

  10. 10. Multiple choice

    An unsorted list of 100 names. Searching one by one, how many comparisons can finding one cost?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →