Start learning free

LESSON 37 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Quantities and a Total in JavaScript

Practice

A cart line is more than a product: it has a quantity. When the same product is added again, you look for its line first and raise the quantity, instead of pushing a second line.

Here is the pattern on a reading list that counts how often each book was opened:

const opened = [];

function openBook(book) {
  const entry = opened.find((e) => e.title === book.title);
  if (entry) entry.times += 1;
  else opened.push({ ...book, times: 1 });
}

find gives the entry, or undefined when there is none. { ...book, times: 1 } is a new object with the book's fields plus times, so book itself never changes. To add up numbers, use reduce with a start value: [3, 4, 5].reduce((sum, n) => sum + n, 0) gives 12, and an empty array gives the start, 0.

The check clicks "Add to cart" in Mug, Lamp and Mug, then "Remove" in the Mug line. Each cart line also shows a button: Remove. It must print:

> open the page                  list (empty)   text: Total: $0
> click "Add to cart" in "Mug"   + item: Mug x 1 $12    + text: Total: $12
> click "Add to cart" in "Lamp"  + item: Lamp x 1 $29   + text: Total: $41
> click "Add to cart" in "Mug"   + item: Mug x 2 $24    + text: Total: $53
> click "Remove" in "Mug x 2"    + text: Cart (1)  - item: Mug x 2 $24  + text: Total: $29

The header's Cart (…) still shows cart.length, so it counts lines, not items: after Mug, Lamp and Mug it stays Cart (2), one line for the Mug and one for the Lamp.

Your task: in cartLine, write the line as Mug x 2 $24 and add a Remove button whose click splices the line out of cart and calls render. In addToCart, raise the quantity of an existing line, or push a copy of the product with quantity: 1. In render, write Total: $ and the sum from reduce.


Assignment
Follow the Coding Tutorial to give each cart line a quantity and a Remove button, and the cart a total.


Hint
In a listener, change only cart, then call render(): the page follows. find returns undefined when there is no line, and undefined counts as false in an if.


STEP 1 OF 12
    Ctrl + Enter to check

    Dom Cart Quantities in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free