Node.js
Calculating totals
Learn to compute the subtotal and the tax-inclusive total.
Calculating totals
To compute the subtotal of the products in the cart we will write a getSubtotal method. Each product contributes p.price * p.quantity; we walk all products and sum these to get the subtotal.
This is a classic accumulation pattern: start with let sum = 0;, walk each product with for...of, and add with sum += p.price * p.quantity. Finally return sum; returns the result. The accumulation pattern will help you with stock counts, averages and many other calculations.
Subtotal vs total
The subtotal is the amount before tax and extra fees. To get the tax-inclusive total you use subtotal * (1 + taxRate); for an 18% tax you apply a 1.18 multiplier.
In this project getSubtotal returns only the subtotal; the taxed total can be computed in main. Separating the two makes it easy to update just the multiplier when the tax rate changes. This separation matters because tax rates vary from country to country.
Exercise Write the getSubtotal method
Add a getSubtotal method to the Cart class. Its signature must be getSubtotal(). In the body start with let sum = 0;, walk each product with for (const p of this.items), add with sum += p.price * p.quantity and return with return sum;. main already adds two products and prints getSubtotal. The output on a single line must be 80.
Show example solution
class Cart {
constructor() {
this.items = [];
}
addItem(product) {
this.items.push(product);
}
getSubtotal() {
let sum = 0;
for (const p of this.items) {
sum += p.price * p.quantity;
}
return sum;
}
}
// Test
const cart = new Cart();
cart.addItem({ name: "Notebook", price: 25, quantity: 2 });
cart.addItem({ name: "Pen", price: 10, quantity: 3 });
console.log(cart.getSubtotal());
Test yourself
-
Write the getSubtotal body
let sum = 0;
for (const p of this.items) {
____;
}
return sum;
Show answer
let sum = 0;
for (const p of this.items) {
sum += p.price * p.quantity;
}
return sum;
-
Match each concept to its meaning
- Subtotal
- Pre-tax total
- Tax
- Tax rate
- Total
- Tax-inclusive total
- Quantity
- Item count
-
What is a product's contribution in the cart?
// product p in the cart
- p.name
- p.price * p.quantity
- p.price + p.quantity
- p.quantity
Show answer
p.price * p.quantity — Unit price times quantity: p.price * p.quantity.
Next lesson: Listing the cart