Project: Shopping cart
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
arraysfor product names and prices - Add products to the cart with
push - List the cart items with a
forloop - Sum prices with a
totalvariable
Ready? Let's start.
Which concepts will you use?
In this project you'll combine concepts you've already learned:
- Variable declaration with
constandlet - Array creation with
[] - Adding items with
push - Iterating with a
forloop andlength - The accumulator pattern:
let total = 0start 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:
- This lesson starts with an empty
cartarray. - Next we'll define
productNamesandproductPricesarrays. - Then we'll
pushitems into the cart and list them with aforloop. - After that we'll sum the prices of the items in the cart.
- 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
-
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.
-
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