JavaScript reduce() Practice: Cart Total
A cart total needs to account for both the unit price and the number of units. This exercise builds an accumulator that turns several cart rows into one value. Start with the arithmetic before choosing between a loop and reduce.
Before you start: Numbers, arrays of objects and multiplication.
Your task
Calculate price × quantity for each item and add the amounts. Try a for...of loop first, then reduce().
Starter code
const cart = [
{ price: 120, quantity: 2 },
{ price: 80, quantity: 1 },
];
// Print the total cost.
Expected result
320Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.
Need a hint?
For each item, add price * quantity to a total that starts at zero.
Show the complete solution and walkthrough
const cart = [
{ price: 120, quantity: 2 },
{ price: 80, quantity: 1 },
];
// Print the total cost.
const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
console.log(total);
- Calculate the first row: 120 multiplied by 2 is 240. The second row is 80 multiplied by 1, which is 80.
- Pass 0 as the initial accumulator to reduce. On each iteration, return the previous total plus the current row amount.
- The final total is 240 + 80, or 320. Print it after the calculation. A for...of loop with the same update is a valid alternative.
A common mistake
Adding only price ignores quantity. Leaving out the initial value makes empty arrays fail and can treat the first object as the accumulator.
Try an edge case
An empty cart returns 0 when the initial value is supplied. A row with quantity 0 contributes nothing. This example assumes valid numeric prices and quantities.
Take it one step further
Write a for...of version, then compare both results for three items. For real currency, consider integer minor units and an explicit rounding policy.