CodeBlanks Logo Icon CodeBlanks

Adding items

Learn to add items with the addItem method.

The addItem method

The Cart class is ready; now we will write an addItem method to add products to the cart. The Cart class's items array is already initialized as empty in the constructor; this array holds the added products.

The addItem(product) method calls this.items.push(product) in its body, which appends the product to the end of the array. A product is an object with { name, price, quantity } fields. For example cart.addItem({ name: "Notebook", price: 25, quantity: 2 }) adds a notebook product.

push and array append

.push(x) appends an element to the end of an array and returns the new length. items.push(product) places product at the end of items; the array length grows by one.

To add several products you call addItem once per product. For example adding two products: cart.addItem(p1); cart.addItem(p2);. Each call places one more element in the items array; insertion order is preserved. push appends at the end; to prepend use unshift.

Practice Write the addItem method

Add an addItem method inside the Cart class. Its signature must be addItem(product). The body should call this.items.push(product);. The main part already adds a product and prints added; you only need to write the method. The output on a single line must be added.

Starter code

index.js
class Cart {
    constructor() {
        this.items = [];
    }
}
    // Write the addItem method here
}

// Test
const cart = new Cart();
cart.addItem({ name: "Notebook", price: 25, quantity: 2 });
console.log("added");

Sample solution

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

// Test
const cart = new Cart();
cart.addItem({ name: "Notebook", price: 25, quantity: 2 });
console.log("added");

Expected output

added

Questions and answers

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

1 Write the addItem body

Question
addItem(product) {
    ____;
}
Answer
addItem(product) {
    this.items.push(product);
}

Explanation: this.items.push(product) appends the product to the array.

2 Match each method to its job

Term Meaning
addItem Adds a product
push Appends to array
constructor Initial setup
this.items Products array

3 What does cart.addItem(p) do?

index.js
cart.addItem(p);
  • Appends p to items Correct answer
  • Prints the cart
  • Removes a product
  • Computes the total

Explanation: addItem appends p to the this.items array.

All lessons in Beginner