CodeBlanks Logo Icon CodeBlanks

Cart design

Design the class structure for the shopping cart.

Cart design

In this project we will build a shopping cart application step by step. The first step is to design the Cart class that will hold the products added to the cart. In JavaScript you use a class to group related data and behavior under one roof; you will see more about classes in a later level.

A cart has an items array that holds the added products. The constructor method runs when a new object is created from the class and initializes items as an empty array. The form is class Cart { constructor() { this.items = []; } }. this refers to the current object.

this and object fields

Inside a class this refers to the current object. Writing this.items reaches that object's items field. Each new Cart() call creates a separate object; each has its own items array.

Defining a field in the constructor ensures all objects created from that class will have it. For example const c1 = new Cart(); const c2 = new Cart(); creates two separate carts; c1.items and c2.items are independent. This is why this is required.

Practice Define the Cart class

Define a Cart class: in the constructor method initialize the items array as empty with this.items = []. The main part already creates a cart and prints cart ready; you only need to define the class. The output on a single line must be cart ready.

Starter code

index.js
// Define the Cart class here

// Test
const cart = new Cart();
console.log("cart ready");

Sample solution

index.js
class Cart {
    constructor() {
        this.items = [];
    }
}

// Test
const cart = new Cart();
console.log("cart ready");

Expected output

cart ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does the constructor run?

index.js
class Cart { constructor() { ... } }
const c = new Cart();
  • When the class is defined
  • At program end
  • When addItem is called
  • When new Cart() is called Correct answer

Explanation: The constructor runs when a new object is created with new Cart().

2 Write the constructor body

Question
class Cart {
    constructor() {
        ____;
    }
}
Answer
class Cart {
    constructor() {
        this.items = [];
    }
}

Explanation: this.items = [] initializes the items array as empty.

3 Match each part to its job

Term Meaning
class Cart Class declaration
constructor() Initial setup
this.items Object field
new Cart() Creates an object

All lessons in Beginner