Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return statement in forEach won't stop execution of function [duplicate]

Tags:

javascript

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?

like image 557
user2422960 Avatar asked Jul 25 '14 09:07

user2422960


People also ask

Why does using return within a foreach loop stop the loop?

Using return within the callback of a forEach () loop does not stop the loop, instead it continues to the next element in the iteration. This happens because forEach () executes the callback function for each element of the array. To demonstrate this, let's look at the following example:

Does foreach() return a value?

In fact, forEach () takes in a callback function that does return a value, but only within the scope created by forEach ().

Why can't I use the break statement in foreach ()?

JavaScript's forEach () function executes a function on every element in an array. However, since forEach () is a function rather than a loop, using the break statement is a syntax error: We recommend using for/of loops to iterate through an array unless you have a good reason not to.

How to break out of a foreach loop in JavaScript?

How to Break Out of a JavaScript forEach () Loop 1. Use every () instead of forEach (). The every () function behaves exactly like forEach (), except it stops iterating... 2. Filter Out The Values You Want to Skip. Instead of thinking about how to break out of a forEach (), try thinking... 3. Use a ...


1 Answers

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

like image 156
Richard Avatar answered Oct 07 '22 13:10

Richard