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:
- Declare a
totalvariable and set it to zero:let total = 0; - Inside the loop, add each value to
total:total += price; - When the loop ends,
totalholds 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:
- Initialize the accumulator with
let total = 0; - Loop through each index in the cart with a
forloop. - 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
-
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.
-
Update the total
let total = 0; ____ console.log("Total:", total);Show answer
let total = 0; total += productPrices[0]; console.log("Total:", total); -
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