Today during our ‘Bug Fix Friday’ we were discussing how to rewrite a rather complex loop construction using a more functional style syntax. As we were all C# developers, the equivalent of what we wanted to achieve in JavaScript was what C# offers through the .Any() LINQ operation.
So the discussion was if their was a similar approach possible in JavaScript?
And the answer is… of course! The Array.prototype.some() method did exactly what we needed.
From MDN:
some()
executes thecallback
function once for each element present in the array until it finds one wherecallback
returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found,some()
immediately returnstrue
. Otherwise,some()
returnsfalse
.callback
is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
An example: