In this video, you searched your train ride playlist for the first song that starts with a given letter, and saw the loop stop as soon as it found one.
Key Points
- A count has to visit every item, because any item it skips might be one more match.
- A search needs only the first match, so it can stop as soon as it finds one. Later items can’t change which match came first.
- A
returninside the loop hands back the matching item and leaves the whole function on the spot, so the loop stops too. It works like abreakthat also hands back the item. - When nothing matches, the
ifcheck is false on every pass, the loop visits every item, and thereturninside it never runs. - The not-found answer comes from a second
returnafter the loop. Only once the loop has checked the last item can the function be sure that nothing matched. Here, that answer isundefined. - An empty list gets the same not-found answer, because the loop makes no passes at all.
Final Code
playlist.js
function firstStartingWith(songs, letter) {
for (const song of songs) {
if (song[0] === letter) {
return song;
}
}
return undefined;
}
const songs = [
"Rainy Day Waltz", "Mountain Echo",
"Last Train Home", "Midnight Ferry"
];
console.log(firstStartingWith(songs, "M"));