forEach returns undefined by specification . If you want to know if there is a specific value in an array, there is indexOf. For more complex problems, there is some function that allows the function to check values ββand returns true the first time the function returns true or false otherwise:
a.some(function(value){return value == 2})
Obviously, this is a trivial case, but consider whether you want to determine if the array contains any even numbers:
a.some(function(value){return !(value % 2)})
or as a function of the arrow ECMA2015:
a.some(value => !(value % 2));
If you want to check if a specific value is repeated in an array, you can use lastIndexOf :
if (a.indexOf(value) != a.lastIndexOf(value) {
or to check for any duplicates, some of them will do the following:
var hasDupes = a.some(function(value, i, a) { return a.lastIndexOf(value) != i; });
The advantage of some and each is that they process only the elements of the array until the condition is satisfied, and then they exit, while forEach will process all the members independently.
source share