Javascript ForEach Gotcha

Here’s a simple gotcha for javascript forEach loops. Take a look at the below function doFoo. You would think that it would return true when it reaches the element in the array that equals 3 however it always returns false. ​

function doFoo() {
var list = [1,2,3,4,5];
list.forEach(function(item) {
if (item == 3) {
return true;
}
});
return false;
}

The “return true” doesnt break out of the doFoo function, it breaks out of the foEach function (which isnt much help). To rewrite with the correct intention we have store the return result in a variable.

function doFoo() {
var list = [1,2,3,4,5];
var result = false;
list.forEach(function(item) {
if (item == 3) {
result = true;
}
});
return result;
}

This is correct but not quite the most efficient as it will still inspect every element in the array.
To make it a little faster we can use every. Here’s the rewritten function:

function doFoo() {
var list = [1,2,3,4,5];
return !list.every(function(item) { item !== 3 });
}

Here we are inspecting each element but when we reach the element that equals 3 the every function will break out of the function returning the result. Also note that we are testing to see if the array contains 3 by testing if every element is not equal to 3.


Originally published at www.nexusconcepts.com.