CodeBlanks Logo Icon CodeBlanks

Project: Shopping cart

JavaScript course · Beginner · Lesson 54/133

Overview of the 5-lesson shopping cart project: add products and compute the total.

Project: Shopping cart

In this 5-lesson project you'll build a shopping cart app. Each lesson adds one piece, and by the final lesson you'll have a complete mini application.

You'll do the following:

  • Define arrays for product names and prices
  • Add products to the cart with push
  • List the cart items with a for loop
  • Sum prices with a total variable

Ready? Let's start.

Which concepts will you use?

In this project you'll combine concepts you've already learned:

  • Variable declaration with const and let
  • Array creation with []
  • Adding items with push
  • Iterating with a for loop and length
  • The accumulator pattern: let total = 0 start and += update

All were covered in earlier lessons; here we combine them for a real goal.

The project plan

We'll go step by step:

  1. This lesson starts with an empty cart array.
  2. Next we'll define productNames and productPrices arrays.
  3. Then we'll push items into the cart and list them with a for loop.
  4. After that we'll sum the prices of the items in the cart.
  5. The final lesson combines everything into a complete app.

Each lesson builds on the previous one's code.

Exercise Declare an empty cart array

As the first step of this project, declare an empty cart array and print it to the console.

Show example solution
// Empty array for the cart
const cart = [];
console.log(cart);

Test yourself

  1. What's the best structure to store 3 product names in a shop?

    • const productNames = ["Pen", "Notebook", "Eraser"]
    • const product1 = "Pen"; const product2 = "Notebook"; const product3 = "Eraser"
    • const products = "Pen Notebook Eraser"
    • console.log("Pen"); console.log("Notebook"); console.log("Eraser")
    Show answer

    const productNames = ["Pen", "Notebook", "Eraser"] — Correct! An array groups values of the same kind under one name and is easy to loop over.

  2. Match the concepts

    cart
    Array that represents the cart
    push
    Method that adds an item to an array
    for
    Loop that iterates over an array
    total
    Variable holding the sum of prices

All lessons in Beginner