Is it there at all?
Show on a big screenA bus fare board lists ticket prices, in no order. Is 21 rupees on it?
- Board: 12, 30, 9, 18, 24, 36, 15.
- Check 12. Not 21. Count 1.
- Check 30. Not 21. Count 2.
- Check 9. Not 21. Count 3.
- Check 18. Not 21. Count 4.
- Check 24. Not 21. Count 5.
- Check 36. Not 21. Count 6.
- Check 15. Not 21. Count 7. Not found.
The rule
No, 21 is not on the board. The steps checked all seven fares.
Walk the list and answer yes or no. Say yes the moment you find it. Say no only after the whole walk.
This is linear search: check each item, one after another. On a board of n fares, it checks at most n times.
Here wanted is the fare to look for. The sign === means is equal to. The word return sends an answer back and ends the call.
`` function found(fares, wanted) { for (const fare of fares) { if (fare === wanted) { return true; } } // what goes here, after the loop? } ``
found(board, 18) gives true at the fourth check, and stops.
For 21, the walk ends with no match. With nothing after the loop, the call gives back nothing. Nothing is not false.
One last line fixes it. That line says false. Then found(board, 21) gives false, after all seven checks.
Finish the walk so it says false for 21.
Loading lab…
Try the lab to finish this lesson.