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.
You could do the following, with
Array#find
:A little more adjustment and you can avoid having
updateCart()
in two different places:If the environment(s) you're targeting do not all support
Array#find
, you can get a polyfill from MDN.To quote Mozilla Developer Network:
Having said that, I believe your solution to have set a flag to return out of the function is the most appropriate and simple.
You could improve by making your cart an object that has methods for adding to it and a
quantities
property. That property would have as keys the different combinations of pizza and size, and as values the quantities for them. This would replace the array you currently have.Then you can access these properties directly without having to loop at all, and without the need for the function
pizzaAndSizeAreTheSame
.Here is an example of you could implement that: