Medium
JavaScript: Calculate Total Price in Shopping Cart Using Array Reduce Method
You’re implementing a shopping cart where the user can add or remove items. After updating the cart, you want to calculate the total price. However, there’s an issue with how prices are being summed up. Can you spot the error?
1const cart = [2 { item: 'Laptop', price: 999.99, quantity: 1 },3 { item: 'Mouse', price: 19.99, quantity: 2 },4 { item: 'Keyboard', price: 49.99, quantity: 1 }5];67const calculateTotal = cart => {8 return cart.reduce((total, item) => {9 return total + item.price * item.quantity;10 }, 0);11};1213console.log(`Total: $${calculateTotal(cart).toFixed(2)}`);