CodeBlanks Logo Icon CodeBlanks

Computing the total

JavaScript course · Beginner · Lesson 57/133

Sum each product's price with a loop to find the cart total.

The accumulator pattern

To sum the numbers in an array, you use the accumulator pattern:

  1. Declare a total variable and set it to zero: let total = 0;
  2. Inside the loop, add each value to total: total += price;
  3. When the loop ends, total holds the sum of all values.

The += operator means "add the right value to the left": total += 5 is the same as total = total + 5.

Computing the cart total

To sum the prices of the products in the cart:

  1. Initialize the accumulator with let total = 0;
  2. Loop through each index in the cart with a for loop.
  3. At each step, add the price with total += productPrices[cart[i]];

Here cart[i] is the product index at position i in the cart; productPrices[cart[i]] gives that product's price. We use two nested indexes.

Exercise Compute the cart total

Declare a let total = 0; variable. Then loop over the cart with a for loop and add each product's price to total (total += productPrices[cart[i]]). After the loop, print the total with console.log.

Show example solution
// Empty array for the cart
const cart = [];
// Product names and prices
const productNames = ["Pen", "Notebook", "Eraser"];
const productPrices = [15, 30, 10];
// Add products to the cart
cart.push(0);
cart.push(2);
// List the products in the cart
for (let i = 0; i < cart.length; i++) {
  console.log(productNames[cart[i]], productPrices[cart[i]]);
}
// Compute the total
let total = 0;
for (let i = 0; i < cart.length; i++) {
  total += productPrices[cart[i]];
}
console.log("Total:", total);

Test yourself

  1. What should the initial value of an accumulator be?

    • An empty array: []
    • 1, because the first product's price is already counted
    • The price of the first product in the cart
    • 0, because summation starts from zero
    Show answer

    0, because summation starts from zero — Correct! Summation starts at zero and grows with each + step.

  2. Update the total

    let total = 0;
    ____
    console.log("Total:", total);
    Show answer
    let total = 0;
    total += productPrices[0];
    console.log("Total:", total);
  3. Match the accumulator pattern

    let total = 0
    Initial value of the accumulator
    total += ...
    Updates the total each step
    for (let i = 0; ...)
    Iterates over the array
    console.log(total)
    Prints the result

All lessons in Beginner