Calculating totals
- Node.js course
- Beginner
- Lesson 50/116
- 6 min
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.
Practice 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.
Starter code
class Cart {
constructor() {
this.items = [];
}
addItem(product) {
this.items.push(product);
}
}
// Write the getSubtotal method here
}
// 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());Sample 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());Expected output
80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the getSubtotal body
let sum = 0;
for (const p of this.items) {
____;
}
return sum;
let sum = 0;
for (const p of this.items) {
sum += p.price * p.quantity;
}
return sum;
Explanation: Each product contributes price * quantity.
2 Match each concept to its meaning
| Term | Meaning |
|---|---|
Subtotal |
Pre-tax total |
Tax |
Tax rate |
Total |
Tax-inclusive total |
Quantity |
Item count |
3 What is a product's contribution in the cart?
// product p in the cart- p.name
- p.price * p.quantity Correct answer
- p.price + p.quantity
- p.quantity
Explanation: Unit price times quantity: p.price * p.quantity.