You Need a Break

In some situations, you want to terminate a for loop before the condition becomes false. For example, let’s say you that want to check whether spaghetti is one of my favorite foods. The author.favoriteFoods array is pretty small in our example code, but let’s say that it’s hundreds of items long (which is probably a better reflection of reality). You can loop through all the items in the array, checking whether each one is 'spaghetti', but you might not need to loop through all the items. If the second item in the array is 'spaghetti', it would be wasteful to loop through all the other items because you already know that “spaghetti” is in the array. In this case, you can use a break (see Listing 7.18).

Listing 7.18 Using a Break ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.