Sharing is caring!

JavaScript project for portfolio: Shopping Cart

JavaScript project for portfolio: Shopping Cart: This is a simple shopping cart that allows users to add products, view the cart, and calculate the total cost.

With a name and a price, the Product class in this code represents a product. Additionally, our ShoppingCart class enables users to add items, view their cart, and determine the final price.

Using the Product class, we create instances of products, and the ShoppingCart class, we create instances of a shopping cart. After that, we view the cart using the viewCart() method, add the products to it using the addProduct() method, and calculate the total price with the calculateTotal() method.

JavaScript code

// Product class
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

// Shopping cart class
class ShoppingCart {
  constructor() {
    this.products = [];
  }

  // Add a product to the cart
  addProduct(product) {
    this.products.push(product);
    console.log(`Added ${product.name} to the cart.`);
  }

  // View the cart
  viewCart() {
    console.log('Shopping Cart:');
    this.products.forEach((product, index) => {
      console.log(`${index + 1}. ${product.name} - $${product.price}`);
    });
  }

  // Calculate the total cost
  calculateTotal() {
    let total = 0;
    this.products.forEach((product) => {
      total += product.price;
    });
    console.log('Total cost: $' + total.toFixed(2));
  }
}

// Create instances of products
const product1 = new Product('Shirt', 20.99);
const product2 = new Product('Pants', 35.99);
const product3 = new Product('Shoes', 49.99);

// Create a shopping cart
const cart = new ShoppingCart();

// Add products to the cart
cart.addProduct(product1);
cart.addProduct(product2);
cart.addProduct(product3);

// View the cart
cart.viewCart();

// Calculate the total cost
cart.calculateTotal();

JavaScript ile neler yapılabilir? JavaScript öğrenmek ne kadar sürer? JavaScript hangi program? JavaScript neden popüler?¿Qué proyectos se pueden hacer con JavaScript? ¿Qué es un proyecto en JavaScript? ¿Cómo empezar un proyecto de JavaScript? ¿Qué programas se han hecho con JavaScript? Wird JavaScript noch benötigt? Was kann man alles mit JavaScript machen? Ist JavaScript für Anfänger? Wie schwierig ist JavaScript? مشاريع جافا سكريبت للمبتدئين مشاريع جافا سكريبت جاهزة pdf مشروع جافا سكريبت javascript مشروع جافا سكريبت github تفعيل جافا سكريبت على الهاتف مشاريع جافا للمبتدئين جافا سكريبت تحميل تحميل جافا سكريبت للاندرويد


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *