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
You could do the following, with Array#find
:
function addToCart(pizza, size)
{
// find the first item where the condition is true,
// or undefined if there is none
var sameSizeItem = Cart.find(function (item) {
return pizzaAndSizeAreTheSame(item, pizza, size);
});
if (sameSizeItem) {
sameSizeItem.quantity++;
updateCart();
return;
}
Cart.push({
pizza: pizza,
size: size,
quantity: 1
});
updateCart();
}
A little more adjustment and you can avoid having updateCart()
in two different places:
function addToCart(pizza, size)
{
// find the first item where the condition is true,
// or undefined if there is none
var sameSizeItem = Cart.find(function (item) {
return pizzaAndSizeAreTheSame(item, pizza, size);
});
if (sameSizeItem) {
sameSizeItem.quantity++;
} else {
Cart.push({
pizza: pizza,
size: size,
quantity: 1
});
}
updateCart();
}
If the environment(s) you're targeting do not all support Array#find
, you can get a polyfill from MDN.