Search code examples
javascriptarraysforeachecmascript-5

Return from a method in which forEach() array method was called. JavaScript


I am using forEach() method called from an array in JavaScript. When I write return; somewhere inside the method which is called for every element in array I return out from the method which was called for a specific element and that is all. But what I actually want is to return out from the method in which array called forEach(). Here is the code:

    function addToCart(pizza, size)
    {
        Cart.forEach(function(cartItem)
        {
            if(pizzaAndSizeAreTheSame(cartItem, pizza, size))
            {
                cartItem.quantity++;
                updateCart();
                //Want go out from addToCart if this return is reached
                return;
            }
        });

        //Don`t want the code run after return;
        Cart.push
        ({
            pizza: pizza,
            size: size,
            quantity: 1
        });
        updateCart();
    }

Here is solution with which I came up so far :

    function addToCart(pizza, size)
{
    var leaveTheMethod = false;
    Cart.forEach(function(cartItem)
    {
        if(pizzaAndSizeAreTheSame(cartItem, pizza, size))
        {
            cartItem.quantity++;
            updateCart();
            leveTheMethod = true;
        }
    });
    if(leaveTheMethod)
        {return;}

    //Don`t want the code run after return;
    Cart.push
    ({
        pizza: pizza,
        size: size,
        quantity: 1
    });
    updateCart();
}

I would like to know are there any better solutions to the problem.

Compared to that question: How to short circuit Array.forEach like calling break? I am not interested in knowing the new method in forEach() loop and I want to break not from forEach() but from encompassing the forEach() caller method.


Solution

  • function addToCart(pizza, size) {
        var res = Cart.some(function(cartItem)) {
            if(pizzaAndSizeAreTheSame(cartItem, pizza, size)) {
                cartItem.quantity++;
                updateCart();
                //Want go out from addToCart if this return is reached
                return true;
            }
            return false;
        });
    
        if(res) {
          return;
        }
        //Don`t want the code run after return;
        Cart.push({
            pizza: pizza,
            size: size,
            quantity: 1
        });
        updateCart();
    }