Iterating an array usually requires counting. This makes sense, because in order to “do something” with every element in the array, you have to know how many elements are in there (i.e. the array’s “length”). Then you have to keep track as you count up to (or down from) the length of the array. This approach is perfectly valid, but it comes with problems.
Using a while-loop – Example # 1
The tedious boilerplate code we discussed above is exactly what you find in Example # 1. We’re using a while-loop to iterate over the someNumbers array. On each iteration of the loop, we use the value of “i” to examine the currently iterated array element and determine if it meets the criteria for our search. This code is valid and it works, but it’s less than optimal.
Using the Array find() method – Example # 2
In Example # 2, we use the Array find() method to eliminate the problems introduced in the previous example. We’ve passed an anonymous function to the Array find() method, and this method takes the currently iterated element as its first argument. Inside of this anonymous function, we provide some logic that determines the currently iterated array element, then we decide whether or not it meets the criteria for our search. The first big benefit here is that we’ve removed the “while” loop. Also, we no longer have the “i” variable. These may seem like small details, but every variable takes up memory, and has scope.