| ok, maybe I'm too aggressive lately, but the only reason to do a break is to stop iterating over the array. You can easily achieve the output of using break using filter, but you cannot achieve the behavior because filter goes over every item in your array. Probably the most common reason you want to break is that you found what you were looking for so find is what you would use. so to make an example that would not be reasonable for find: you have a long array of objects, you need to display 5 of the 'interesting' objects out of this array. What constitutes 'interesting' is determined by some relatively complicated logic on each item in the array. Since you do not know how many items in this array are interesting you want to process all items until you have 5 items. When you have 5 items you want to stop processing items therefore you break, if your first 5 items have the property of being 'interesting' you just saved a lot of work in your application and things feel zippy so you want to do that (because your application maybe needs the help at this point) It is obviously, as all examples when one does not need something at the very moment, somewhat artificial - but I would say it is not unthinkable. However, as I made clear earlier, I am not arguing for the necessity of break - if I wanted to do what I just described I would probably use while unless the syntax became unwieldy - I dislike break. The only reason I got into this is because someone said they didn't believe most programmers wouldn't ever need break (which can be used to stop iteration of an array) and the guy who said all most programmers needed was map and reduce (both of which iterate over every item of an array) then said they never said most programmers wouldn't need break. |
Because JS’s map and filter provide the index and array as arguments, you can, in fact, achieve the behavior of break. If you need the original array after the iteration, you need to apply the map or filter to a copy, though, because the way to achieve the behavior of break involves modifying the array by deleting all the items after the current one, which stops the iteration.