Or how to write a one-liner and still keep your code expressive.
Here's that one-liner.
const containsNumbers = !someArr.some(isNaN)
What's going on here?
First, our array uses the
some method. This method loops over the array and accepts a function that tests if at least one element passes the criteria set by that function.
Notice "at least one" element part. Let's say you used
filter method instead of
some. Now let's pretend that you are looping over a large array but you are only interested in first occurrence of a number. Why take the performance hit and loop over an entire array, right? So you would have to manually exit the loop based on a condition. Not with
some, it is handled for you.
The second part is a callback function. We can rely on the global (window)
isNaN function here. Keep in mind that there is also
Number.isNaN method that provides more predictable results when it comes to type coercion. Use whatever is more appropriate in your case, but note that the global
isNaN function has better browser support.
In and out. Ciao!