CodeBlanks Logo Icon CodeBlanks

Computing the total

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.

Practice 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.

Starter code

script.js
// 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

Sample solution

script.js
// 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);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should the initial value of an accumulator be?

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

Explanation: Summation starts at zero and grows with each + step.

2 Update the total

Question
let total = 0;
____
console.log("Total:", total);
Answer
let total = 0;
total += productPrices[0];
console.log("Total:", total);

Explanation: The += operator adds the right side to the left side.

3 Match the accumulator pattern

Term Meaning
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