Start learning free

LESSON 189 OF 671 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in JavaScript: Sum the Cart with a for Loop

Practice Read the full explanation

Use a for loop over parallel arrays to compute a running total across several items.

You start with:

const items = ["Shirt", "Pants", "Shoes", "Hat"];
const prices = [25, 40, 60, 15];
const quantities = [2, 1, 1, 3];

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with console.log(result).

Start with const lines = []; let total = 0; before the loop, then push each formatted line and add to total.

Call lines.join("\n") at the end.

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);

STEP 1 OF 9
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in JavaScript, explained

    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 lines array that collects one formatted row per item.
    • A total number 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

    1. Create lines as an empty array. It is a const, because the loop adds elements to the same array and never replaces it with another one.
    2. Create total with let and start it at 0. It changes on every pass, so const won't do.
    3. Write the for loop. The index i starts at 0 and the loop continues while i < items.length. For four items, i takes the values 0, 1, 2 and 3.
    4. Compute the item's subtotal in a constant named sub: prices[i] times quantities[i].
    5. Add sub to total. After each pass, total holds the sum of all the items seen so far.
    6. Push the row onto lines: name, a space, x, the quantity, a colon, a space, a dollar sign and the subtotal, all glued with +.
    7. After the loop, push the Total row. It sits outside the braces so that it runs once.
    8. Build result with lines.join("\n").
    9. 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.

    iItemsubtotal after the pass
    0Shirt5050
    1Pants4090
    2Shoes60150
    3Hat45195

    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 Total row inside the loop. It would appear once per item, with a partial sum each time.
    • Using <= in the loop condition. At i === items.length the arrays have nothing to read: items[4] is undefined, and the row would start with undefined, while the multiplication gives NaN.
    • Forgetting to reset or initialise total. Without let total = 0;, adding to it fails, because the name doesn't exist.
    • Declaring total inside 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 * 3 is 0.30000000000000004. The lesson uses whole dollars, so this doesn't show up here. With cents, round for display, for example with toFixed(2).
    • Arrays of different lengths. The loop trusts items.length. If prices were shorter, prices[i] would be undefined and the subtotal would be NaN.
    • 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
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free