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.
pizzaAndSizeAreTheSamecomparing to check if something is found? If so then usefindorsome!.some()is what you're looking for. If the callback returnstrue, the iteration stops and.some()also returnstrue.