Learn Basic OOP by Building a Shopping Cart - Step 55

Tell us what’s happening: I have a issue with if statement with this.items array I don’t see the error

const productsContainer = document.getElementById("products-container");
const dessertCards = document.getElementById("dessert-card-container");
const cartBtn = document.getElementById("cart-btn");
const clearCartBtn = document.getElementById("clear-cart-btn");
const totalNumberOfItems = document.getElementById("total-items");
const cartSubTotal = document.getElementById("subtotal");
const cartTaxes = document.getElementById("taxes");
const cartTotal = document.getElementById("total");
const showHideCartSpan = document.getElementById("show-hide-cart");
let isCartShowing = false;

const products = [
 {
   id: 1,
   name: "Vanilla Cupcakes (6 Pack)",
   price: 12.99,
   category: "Cupcake",
 },
 {
   id: 2,
   name: "French Macaron",
   price: 3.99,
   category: "Macaron",
 },
 {
   id: 3,
   name: "Pumpkin Cupcake",
   price: 3.99,
   category: "Cupcake",
 },
 {
   id: 4,
   name: "Chocolate Cupcake",
   price: 5.99,
   category: "Cupcake",
 },
 {
   id: 5,
   name: "Chocolate Pretzels (4 Pack)",
   price: 10.99,
   category: "Pretzel",
 },
 {
   id: 6,
   name: "Strawberry Ice Cream",
   price: 2.99,
   category: "Ice Cream",
 },
 {
   id: 7,
   name: "Chocolate Macarons (4 Pack)",
   price: 9.99,
   category: "Macaron",
 },
 {
   id: 8,
   name: "Strawberry Pretzel",
   price: 4.99,
   category: "Pretzel",
 },
 {
   id: 9,
   name: "Butter Pecan Ice Cream",
   price: 2.99,
   category: "Ice Cream",
 },
 {
   id: 10,
   name: "Rocky Road Ice Cream",
   price: 2.99,
   category: "Ice Cream",
 },
 {
   id: 11,
   name: "Vanilla Macarons (5 Pack)",
   price: 11.99,
   category: "Macaron",
 },
 {
   id: 12,
   name: "Lemon Cupcakes (4 Pack)",
   price: 12.99,
   category: "Cupcake",
 },
];

products.forEach(
 ({ name, id, price, category }) => {
   dessertCards.innerHTML += `
     <div class="dessert-card">
       <h2>${name}</h2>
       <p class="dessert-price">$${price}</p>
       <p class="product-category">Category: ${category}</p>
       <button 
         id="${id}" 
         class="btn add-to-cart-btn">Add to cart
       </button>
     </div>
   `;
 }
);

class ShoppingCart {
 constructor() {
   this.items = [];
   this.total = 0;
   this.taxRate = 8.25;
 }

 addItem(id, products) {
   const product = products.find((item) => item.id === id);
   const { name, price } = product;
   this.items.push(product);

   const totalCountPerProduct = {};
   this.items.forEach((dessert) => {
     totalCountPerProduct[dessert.id] = (totalCountPerProduct[dessert.id] || 0) + 1;
   })

   const currentProductCount = totalCountPerProduct[product.id];
   const currentProductCountSpan = document.getElementById(`product-count-for-id${id}`);

   currentProductCount > 1 
     ? currentProductCountSpan.textContent = `${currentProductCount}x`
     : productsContainer.innerHTML += `
     <div id=dessert${id} class="product">
       <p>
         <span class="product-count" id=product-count-for-id${id}></span>${name}
       </p>
       <p>${price}</p>
     </div>
     `;
 }

 getCounts() {
   return this.items.length;
 }

 clearCart() {
     if(!this.items!==[]){
          alert("Your shopping cart is already empty");
          return ;
     }
 }

 calculateTaxes(amount) {
   return parseFloat(((this.taxRate / 100) * amount).toFixed(2));
 }

 calculateTotal() {
   const subTotal = this.items.reduce((total, item) => total + item.price, 0);
   const tax = this.calculateTaxes(subTotal);
   this.total = subTotal + tax;
   cartSubTotal.textContent = `$${subTotal.toFixed(2)}`;
   cartTaxes.textContent = `$${tax.toFixed(2)}`;
   cartTotal.textContent = `$${this.total.toFixed(2)}`;
   return this.total;
 }
};

const cart = new ShoppingCart();
const addToCartBtns = document.getElementsByClassName("add-to-cart-btn");

[...addToCartBtns].forEach(
 (btn) => {
   btn.addEventListener("click", (event) => {
     cart.addItem(Number(event.target.id), products);
     totalNumberOfItems.textContent = cart.getCounts();
     cart.calculateTotal();
   })
 }
);

cartBtn.addEventListener("click", () => {
 isCartShowing = !isCartShowing;
 showHideCartSpan.textContent = isCartShowing ? "Hide" : "Show";
 cartContainer.style.display = isCartShowing ? "block" : "none";
});```



WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

```text
Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36

Challenge Information:

Learn Basic OOP by Building a Shopping Cart - Step 55

in JavaScript this will not work. To check if an array is empty you need to check its length

that’s what this sentence means:

Remember that 0 is a falsy value, so you can use the ! operator to check if the array is empty.

If you want to check if an array is empty, you can use the “length” property.
so for example an array named arr, you can do:

if(arr.length === 0)
or for short
if(!arr.length)
as “0” is a falsy value

Back to your example,
you want to check if the array is empty

so here is a way to do it:

REDACTED SOLUTION

if it’s empty, the “length” property will return 0 which is a falsy value, then the negation operator ‘!’ will make it true. So, the whole if statement check if it’s empty and do the rest of code.

you can read this: MDN documentation

If you still do not understand, ask me more.

2 Likes

@MostafaElbadry

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

1 Like

Sorry about that, i will be more careful next time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.