Problem overview
The cart is described by three parallel arrays: items, prices and quantities. The item at index i in one array matches the price and quantity at index i in the others. The program prints one line per item, in the form Shirt x2: $50, followed by a final Total line that adds up all the item subtotals.
With the starting data, the output is:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
Each line's amount is prices[i] * quantities[i]. The shirts cost 25 each and there are 2 of them, which gives 50. The totals 50, 40, 60 and 45 add up to 195.
Approach: one pass, two jobs per item
The previous version handled a single total. With several items the code would repeat itself, once per item. A loop fixes that: it runs the same few lines for each position and keeps two things up to date as it goes.
- A
linesarray that collects one formatted row per item. - A
totalnumber that is the running sum of the subtotals.
The Total row can only be written once every item has been added, so it is pushed after the loop. Joining the rows into one string is the last step.
Step by step
- Create
linesas an empty array. It is aconst, because the loop adds elements to the same array and never replaces it with another one. - Create
totalwithletand start it at 0. It changes on every pass, soconstwon't do. - Write the
forloop. The indexistarts at 0 and the loop continues whilei < items.length. For four items,itakes the values 0, 1, 2 and 3. - Compute the item's subtotal in a constant named
sub:prices[i]timesquantities[i]. - Add
subtototal. After each pass,totalholds the sum of all the items seen so far. - Push the row onto
lines: name, a space,x, the quantity, a colon, a space, a dollar sign and the subtotal, all glued with+. - After the loop, push the
Totalrow. It sits outside the braces so that it runs once. - Build
resultwithlines.join("\n"). - Print it with
console.log(result).
The solution in JavaScript
const items = ["Shirt", "Pants", "Shoes", "Hat"];
const prices = [25, 40, 60, 15];
const quantities = [2, 1, 1, 3];
const lines = [];
let total = 0;
for (let i = 0; i < items.length; i++) {
const sub = prices[i] * quantities[i];
total = total + sub;
lines.push(items[i] + " x" + quantities[i] + ": $" + sub);
}
lines.push("Total: $" + total);
const result = lines.join("\n");
console.log(result);
What happens on each pass
This table shows the loop with the lesson's data. sub is the item's subtotal, and total is the running sum after that pass.
| i | Item | sub | total after the pass |
|---|---|---|---|
| 0 | Shirt | 50 | 50 |
| 1 | Pants | 40 | 90 |
| 2 | Shoes | 60 | 150 |
| 3 | Hat | 45 | 195 |
After the pass for i = 3, the loop condition 4 < 4 is false, the loop ends, and the Total row uses the final 195.
Details worth knowing
lines.join("\n") puts its argument between each pair of neighbouring elements and nowhere else. The result therefore has no trailing newline, and a one-element array joins to just that element. A const array can still be changed with push: const only stops the name from being reassigned.
The loop goes over positions instead of values because the data is split across three arrays. A for...of loop would give the name but not the price or the quantity. The loop index is what links them. This design only works when the arrays have the same length and the same order, so an extra price at the end of one array would silently shift or hide data.
The row is built from five pieces: items[i], " x", quantities[i], ": $" and sub. Notice the space before the x and the space after the colon. Both are part of the required format.
Complexity
The loop runs once per item and does a constant amount of work in each pass, so the time is O(n) for n items. The lines array holds one string per item plus the total row, so the extra space is also O(n).
Edge cases and common mistakes
- Pushing the
Totalrow inside the loop. It would appear once per item, with a partial sum each time. - Using
<=in the loop condition. Ati === items.lengththe arrays have nothing to read:items[4]isundefined, and the row would start withundefined, while the multiplication givesNaN. - Forgetting to reset or initialise
total. Withoutlet total = 0;, adding to it fails, because the name doesn't exist. - Declaring
totalinside the loop. It would restart from 0 each time. - Decimal prices. JavaScript numbers are binary floating-point, so some sums are slightly off:
0.1 * 3is0.30000000000000004. The lesson uses whole dollars, so this doesn't show up here. With cents, round for display, for example withtoFixed(2). - Arrays of different lengths. The loop trusts
items.length. Ifpriceswere shorter,prices[i]would beundefinedand the subtotal would beNaN. - Empty arrays. The loop never runs, and the output is just
Total: $0.
Testing
Try these data sets in the editor above. For items = ["Cup", "Mug"], prices = [4, 7] and quantities = [3, 2] the output is:
Cup x3: $12
Mug x2: $14
Total: $26
With all three arrays empty ([]), the output is:
Total: $0
