Start learning free

LESSON 192 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in TypeScript: Summing a 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: string[] = ["Shirt", "Pants", "Shoes", "Hat"];
const prices: number[] = [25, 40, 60, 15];
const quantities: number[] = [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: string[] = []; let total = 0; before the loop, then push each formatted line and add to total.

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

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

const lines: string[] = [];
let total: number = 0;
for (let i = 0; i < items.length; i++) {
    const sub: number = prices[i] * quantities[i];
    total = total + sub;
    lines.push(items[i] + " x" + quantities[i] + ": $" + sub);
}
lines.push("Total: $" + total);
const result: string = lines.join("\n");
console.log(result);

STEP 1 OF 9
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in TypeScript, explained

    Problem overview

    The cart now holds several items, stored in three parallel arrays: items (names), prices (price of one unit) and quantities (how many of each). The item at position 0 is a Shirt that costs 25 and was bought twice, the item at position 1 is Pants, and so on. The program must print one receipt line per item in the form Name xQ: $subtotal, then a final Total line, all joined by newlines into a string result that is printed with console.log.

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

    The earlier versions handled one item and a shipping rule. This one repeats the same work for every item, so a loop is the natural tool.

    Approach: one pass with a running total

    Three arrays that line up by position are called parallel arrays: index i in each of them describes the same item. A for loop from 0 to items.length - 1 visits every position, and inside it prices[i] * quantities[i] is that item's subtotal.

    Two things have to be collected while the loop runs. The first is the list of receipt lines, kept in an array of strings called lines. The second is the running total, a number that starts at 0 and grows by each subtotal. The total line only makes sense once every item has been added, so it is pushed after the loop, not inside it.

    Tracing the loop on the starter data gives these values:

    iitemsubtotal after
    0Shirt5050
    1Pants4090
    2Shoes60150
    3Hat45195

    Step by step

    1. Create lines as an empty string[]. Declaring it with const is fine: the array itself is never replaced, only added to.
    2. Create total with let and start it at 0. It changes on every pass, so it can't be a const.
    3. Write the loop for (let i = 0; i < items.length; i++), and close its brace immediately. The condition i < items.length stops after the last valid index.
    4. Compute sub inside the loop: the price times the quantity at the same index.
    5. Add sub to total.
    6. Push the item's row onto lines: the name, a space and x, the quantity, a colon and space, a dollar sign and the subtotal. The + operator turns the numbers into text.
    7. After the loop, push the Total row. It runs once, so it sits outside the braces.
    8. Join the rows into result with lines.join("\n").
    9. Print result.

    The solution in TypeScript

    const items: string[] = ["Shirt", "Pants", "Shoes", "Hat"];
    const prices: number[] = [25, 40, 60, 15];
    const quantities: number[] = [2, 1, 1, 3];
    
    const lines: string[] = [];
    let total: number = 0;
    for (let i = 0; i < items.length; i++) {
        const sub: number = prices[i] * quantities[i];
        total = total + sub;
        lines.push(items[i] + " x" + quantities[i] + ": $" + sub);
    }
    lines.push("Total: $" + total);
    const result: string = lines.join("\n");
    console.log(result);

    Details that matter in TypeScript:

    • join puts its separator only between elements. The result has no newline after the last row, which is what the output needs. Building the string with result += row + "\n" would leave a trailing newline.
    • Array indexing is not checked at run time. If prices were shorter than items, prices[i] would be undefined, and undefined * 2 is NaN. The loop would not stop with an error. The three arrays have to stay the same length.
    • The annotations, such as string[] and number, are erased when the code is compiled. They document the code and let the compiler flag mistakes, but they do not convert anything.
    • The same job could use for...of or forEach, but both give the item rather than its position, and this lesson needs the position to reach all three arrays. A plain indexed loop is the right fit.

    Complexity

    The loop runs once per item and does a constant amount of work each time, so the time is O(n) for n items. join also touches each row once. The extra space is O(n) for the lines array.

    Edge cases and common mistakes

    • Putting the Total push inside the loop. The receipt would then have a Total row after every item.
    • Forgetting to reset total. It must start at 0 before the loop, not inside it, or each pass would throw away the earlier sum.
    • Using <= in the loop condition. Index 4 doesn't exist, so items[4] is undefined. The extra row reads undefined xundefined: $NaN, and the Total line becomes Total: $NaN too, because one NaN poisons every sum it joins.
    • An empty cart. With three empty arrays the loop body never runs and the output is just Total: $0.
    • Decimal prices. Doubles can't store most decimals exactly. With prices [19.99, 5.1, 60, 0.1] and quantities [3, 3, 1, 3], the Pants row prints $15.299999999999999 and the Hat row $0.30000000000000004. Round for display, for example with toFixed(2), or keep amounts in cents. The lesson's whole-number prices stay exact.

    Testing

    Change the arrays in the editor above and compare with these results, produced by the reference solution:

    • Three empty arrays print Total: $0.
    • One item, ["Hat"] with price [15] and quantity [3], prints a Hat x3: $45 row and then Total: $45. The total always equals the sum of the rows above it.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free