Adding products to the cart
Add products to the cart with push and list them with a loop.
Adding items with push
To add an element to the end of an array, you use the push method:
cart.push(0); — appends the value 0 to the cart array.
In our cart, the value we store is a product index. So cart.push(0) means "add the Pen product to the cart", because productNames[0] is the first product's name.
To add several products, you can call push once for each.
Filling the cart with indexes
To add a product to the cart, we push its index. For example:
cart.push(0); — Pen (15)cart.push(2); — Eraser (10)
The cart now contains [0, 2], meaning "one Pen and one Eraser". The cart's length property tells how many items were added.
With a for loop we can walk through each index in the cart and print the matching name and price.
Exercise Add two products to the cart and list them with a loop
Now use push to add two product indexes to the cart array (e.g. 0 and 2). Then loop over the cart with a for loop and print each product's name and price with console.log.
Show example solution
// Empty array for the cart
const cart = [];
// Product names and prices
const productNames = ["Pen", "Notebook", "Eraser"];
const productPrices = [15, 30, 10];
// Add products to the cart
cart.push(0);
cart.push(2);
// List the products in the cart
for (let i = 0; i < cart.length; i++) {
console.log(productNames[cart[i]], productPrices[cart[i]]);
}
Test yourself
-
What does cart.push(2) do?
- Places an element at index 2 of cart
- Removes the element at index 2 from cart
- Appends the value 2 to the end of cart
- Returns the element at index 2 of cart
Show answer
Appends the value 2 to the end of cart — Correct! push appends the given value to the array.
-
Complete the push call
const cart = []; cart.____(0);Show answer
const cart = []; cart.push(0); -
Match the expression to its meaning
- cart.length
- Number of items in the cart
- cart.push(1)
- Adds the second product to the cart
- productNames[0]
- Name of the first product
- productPrices[2]
- Price of the third product