user2422960 user2422960 - 21 days ago 7
Javascript Question

return statement in forEach won't stop execution of function

I am trying to determine whether or not an array holds a certain item. If it does, I would like to hold the function, otherwise it should get added.

function addPacking(item){

data.packings.forEach(function(entry){
if(item.name == entry.name){
return;
}
});

data.packings.push(item);

}


Unfortunately, the data is pushed even when the if condition is met. How do I prevent this behaviour without using an
else
condition?

(I do not want to use
else
because my actual code is a lot more complex than this and I'd like to keep it readable)

Edit:

Does
forEach
execute asynchronously?

Answer

Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach. The return within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking. This can be done using a simply for loop.

function addPacking(item){
    for (var i = 0; i < data.packings.length++; i++) {
        if (item.name == data.packings[i].name) {
            return;
        }
    }

    data.packings.push(item);
});

This approach also supports older browsers, unlike some, every and forEach