JavaScript function that could be used to add a product to the shopping cart

This function could be called from a button on the product page, or from anywhere else on the website where the user can add a product to the shopping cart.

function addToCart(productId) {
  // Get the current contents of the shopping cart.
  const cartItems = JSON.parse(localStorage.getItem('cartItems')) || [];

  // Add the new product to the shopping cart.
  cartItems.push({
    id: productId,
    quantity: 1,
  });

  // Save the updated shopping cart to local storage.
  localStorage.setItem('cartItems', JSON.stringify(cartItems));

  // Show a success message to the user.
  alert('Product added to cart!');
}

Read More Topics

System Design Syllabus

Introduction to System Design

Architectural Patterns in System Design

Scalability and Performance in System Design

Database Design in System Design

Distributed Systems in System Design

System Integration and APIs in System Design

Cloud Computing in Sestem Design

Containerization and Orchestration in System Design

High Availability and Disaster Recovery

Security in System Design

Performance Tuning and Optimization

Case Studies and Real-World Projects

B.Tech 4 YEAR CS/IT PROJECTS And Placement

Face Detection Project Idea

Weather Forecasting APP in MERN Project

JavaScript Tips and Trick

Leave a Comment

Skip to content