Untitled

 avatar
unknown
plain_text
2 years ago
1.2 kB
5
Indexable
// Function to handle adding items to the shopping cart
function addToCart(itemName, itemPrice) {
  // Check if shopping cart exists in local storage
  let cart = localStorage.getItem('cart');
  if (!cart) {
    cart = [];
  } else {
    cart = JSON.parse(cart);
  }

  // Create an object for the new item
  const newItem = {
    name: itemName,
    price: itemPrice
  };

  // Add the new item to the cart
  cart.push(newItem);

  // Store the updated cart in local storage
  localStorage.setItem('cart', JSON.stringify(cart));

  // Display a success message to the user
  alert('Item added to cart!');
}

// Function to display the items in the shopping cart
function displayCart() {
  // Retrieve the cart from local storage
  let cart = localStorage.getItem('cart');
  if (!cart) {
    cart = [];
  } else {
    cart = JSON.parse(cart);
  }

  // Check if the cart is empty
  if (cart.length === 0) {
    console.log('The cart is empty.');
  } else {
    // Display each item in the cart
    console.log('Items in the cart:');
    cart.forEach(item => {
      console.log(`${item.name} - $${item.price}`);
    });
  }
}

// Example usage:
addToCart('T-Shirt', 19.99);
addToCart('Jeans', 49.99);
displayCart();
Editor is loading...