Your cart

Your cart is empty πŸ›’
Total items (unique) 0

Loading Article

Fetching content from our servers...

JavaScript E-commerce Project – Search, Filter & Add to Cart

Learn to build a JavaScript e-commerce product page with search, category and price filters, sorting, ratings, Add to Cart, and LocalStorage. Includes complete source code.

JavaScript E-commerce Product Page Project – Search, Filter, Sort & Add to Cart Using LocalStorage

Learn how to build a complete e-commerce product listing page using HTML, CSS, and Vanilla JavaScript. In this beginner-friendly project, you will create product cards, search products, filter by category and price, sort products, manage a shopping cart, update quantities, calculate totals, and save cart data using LocalStorage.

What Are We Going to Learn in This Project?

In this project, we will build a product page similar to the product listing pages you see on online shopping websites.

Instead of learning JavaScript concepts only through small examples, we will use them to build a practical project.

By completing this project, you will understand how JavaScript handles products, filters, user interactions, cart operations, and browser storage.

JavaScript Concepts We Will Learn

  1. JavaScript Arrays: Store multiple product objects in an array.
  2. JavaScript Objects: Store product information such as name, price, category, rating, and stock status.
  3. DOM Manipulation: Display products dynamically on the webpage.
  4. Array map(): Understand how to transform array data.
  5. Array filter(): Filter products according to user selections.
  6. Array sort(): Sort products by price and rating.
  7. Array find(): Find a particular product using its ID.
  8. Array reduce(): Calculate the total cart price.
  9. Event Listeners: Handle search, filters, buttons, and cart interactions.
  10. Template Literals: Generate dynamic HTML.
  11. JSON: Convert JavaScript data into a format that can be stored.
  12. LocalStorage: Save cart data in the browser and restore it after refreshing the page.
  13. Conditional Statements: Handle product availability and cart conditions.
  14. Functions: Organize our code into reusable functions.

Features We Are Going to Build

Here is what our final product page will include:

FeatureWhat it doesProduct ListingDisplays all available productsSearch ProductsSearches products by nameCategory FilterFilters products by categoryMinimum PriceShows products above a selected priceMaximum PriceShows products below a selected priceRating FilterDisplays products with a minimum ratingStock FilterShows only products that are in stockSortingSorts products by price or ratingAdd to CartAdds a product to the shopping cartQuantity ManagementIncreases or decreases product quantityRemove ProductRemoves an item from the cartCart TotalCalculates the total shopping amountLocalStorageSaves cart data after page refreshReset FiltersResets all product filters

1. What Are We Building?

We are going to build a simple e-commerce product listing page.

Imagine a customer visits an online shopping website. The customer can:

All these operations will happen using JavaScript.

Important: We are building a frontend learning project. LocalStorage is not a replacement for a real shopping website's backend, database, or payment system.

2. Project Folder Structure

Create a folder named

javascript-ecommerce-project

.

Inside it, create these three files:

javascript-ecommerce-project/
β”‚
β”œβ”€β”€ index.html
β”œβ”€β”€ style.css
└── script.js

You can open the project using VS Code and run it with the Live Server extension.

3. Create the HTML Structure

First, we need to create the structure of our product page.

Open

index.html

and write the following code:

JavaScript E-commerce ProjectShopEasy
            Cart: 0Find ProductsAll CategoriesElectronicsFashionAccessoriesAll Ratings3+ Stars4+ Stars4.5+ Stars
                In-stock products only
            Default SortingPrice: Low to HighPrice: High to LowRating: High to LowReset FiltersOur Products0 products foundShopping CartTotal: β‚Ή0
            

            Clear Cart

        

    

    


Understanding the HTML

Let's understand the important parts.

1. Search input

This input allows customers to search for products by name.

For example, if a customer types

Laptop

, JavaScript will display matching laptop products.

2. Category filter


    All Categories
    Electronics
    Fashion

The

select

element creates a dropdown.

When a customer selects Electronics, we will display only products belonging to that category.

3. Price filter


These inputs allow customers to enter a minimum and maximum price.

For example:

The page should display products priced between β‚Ή500 and β‚Ή2,000.

4. Product list

This is an empty container.

JavaScript will generate product cards and insert them into this container dynamically.

5. Shopping cart

JavaScript will display the products added to the cart inside this element.

4. Add CSS Styling

Now open

style.css

and add the following code.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background: #f5f6fa;
    color: #222;
}

.header {
    background: #172554;
    color: white;
    padding: 20px 5%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.cart-indicator {
    background: white;
    color: #172554;
    padding: 10px 16px;
    border-radius: 6px;
    font-weight: bold;
}

.container {
    width: 90%;
    max-width: 1200px;
    margin: 30px auto;
}

.filters {
    background: white;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 30px;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
    align-items: center;
}

.filters h2 {
    grid-column: 1 / -1;
}

.filters input,
.filters select,
.filters button {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.price-filter {
    display: flex;
    gap: 8px;
}

.stock-option {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
}

.stock-option input {
    width: auto;
}

button {
    cursor: pointer;
    border: none;
}

#reset-filters,
#clear-cart {
    background: #172554;
    color: white;
}

.product-section {
    margin-bottom: 40px;
}

.section-heading {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
}

.product-card {
    background: white;
    border-radius: 10px;
    padding: 18px;
    box-shadow: 0 3px 12px rgba(0, 0, 0, 0.06);
}

.product-image {
    height: 130px;
    display: grid;
    place-items: center;
    background: #eef2ff;
    font-size: 55px;
    border-radius: 8px;
    margin-bottom: 15px;
}

.product-card h3 {
    margin-bottom: 10px;
}

.product-card p {
    margin: 8px 0;
    color: #555;
}

.product-card button {
    width: 100%;
    background: #2563eb;
    color: white;
    padding: 11px;
    border-radius: 6px;
    margin-top: 10px;
}

.product-card button:disabled {
    background: #999;
    cursor: not-allowed;
}

.cart-section {
    background: white;
    padding: 20px;
    border-radius: 10px;
    margin-bottom: 40px;
}

.cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
    border-bottom: 1px solid #eee;
    padding: 15px 0;
}

.cart-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.cart-actions button {
    padding: 7px 12px;
    background: #e2e8f0;
    border-radius: 5px;
}

.cart-actions .remove-button {
    background: #fee2e2;
    color: #b91c1c;
}

.cart-total {
    text-align: right;
    margin: 20px 0;
}

.empty-message {
    padding: 20px;
    color: #777;
    text-align: center;
    background: #f8fafc;
    border-radius: 8px;
}

@media (max-width: 600px) {
    .header {
        padding: 15px;
    }

    .container {
        width: 94%;
    }

    .section-heading {
        align-items: flex-start;
        flex-direction: column;
        gap: 8px;
    }

    .cart-item {
        align-items: flex-start;
        flex-direction: column;
    }

    .price-filter {
        flex-direction: column;
    }
}

What Does CSS Grid Do Here?

.product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
}

This CSS creates a responsive product layout.

Now let's build the actual JavaScript functionality.

5. Create Product Data Using JavaScript Objects

Open

script.js

.

First, we need some products to display.

const products = [
    {
        id: 1,
        name: "Wireless Headphones",
        price: 1499,
        category: "Electronics",
        rating: 4.5,
        inStock: true,
        image: "🎧"
    },
    {
        id: 2,
        name: "Smart Watch",
        price: 2499,
        category: "Electronics",
        rating: 4.2,
        inStock: true,
        image: "⌚"
    },
    {
        id: 3,
        name: "Running Shoes",
        price: 1999,
        category: "Fashion",
        rating: 4.7,
        inStock: true,
        image: "πŸ‘Ÿ"
    },
    {
        id: 4,
        name: "Casual T-Shirt",
        price: 599,
        category: "Fashion",
        rating: 4.0,
        inStock: false,
        image: "πŸ‘•"
    },
    {
        id: 5,
        name: "Laptop",
        price: 45999,
        category: "Electronics",
        rating: 4.8,
        inStock: true,
        image: "πŸ’»"
    },
    {
        id: 6,
        name: "Backpack",
        price: 1299,
        category: "Accessories",
        rating: 4.1,
        inStock: true,
        image: "πŸŽ’"
    },
    {
        id: 7,
        name: "Sunglasses",
        price: 899,
        category: "Accessories",
        rating: 3.9,
        inStock: true,
        image: "πŸ•ΆοΈ"
    },
    {
        id: 8,
        name: "Bluetooth Speaker",
        price: 1799,
        category: "Electronics",
        rating: 4.3,
        inStock: false,
        image: "πŸ”Š"
    },
    {
        id: 9,
        name: "Denim Jacket",
        price: 2299,
        category: "Fashion",
        rating: 4.6,
        inStock: true,
        image: "πŸ§₯"
    },
    {
        id: 10,
        name: "Leather Wallet",
        price: 799,
        category: "Accessories",
        rating: 4.4,
        inStock: true,
        image: "πŸ‘›"
    },
    {
        id: 11,
        name: "Gaming Mouse",
        price: 999,
        category: "Electronics",
        rating: 4.5,
        inStock: true,
        image: "πŸ–±οΈ"
    },
    {
        id: 12,
        name: "Sports Cap",
        price: 499,
        category: "Fashion",
        rating: 3.8,
        inStock: true,
        image: "🧒"
    }
];

Understanding the Product Array

Let's understand one product:

{
    id: 1,
    name: "Wireless Headphones",
    price: 1499,
    category: "Electronics",
    rating: 4.5,
    inStock: true,
    image: "🎧"
}

This is a JavaScript object.

Each property stores a different piece of information:

PropertyPurpose

id

Unique product identification

name

Product name

price

Product price

category

Product category

rating

Customer rating

inStock

Product availability

image

Product image representation

Why are we using an array of objects?

Because an e-commerce website contains multiple products, and each product has multiple properties.

An array allows us to store all products in one place and use JavaScript methods to search, filter, sort, and find them.

For this learning project, emojis represent product images. You can replace them with real image URLs later.

6. Select HTML Elements Using JavaScript

Before implementing functionality, we need to access the HTML elements.

Add this below the products array:

const productList = document.getElementById("product-list");

const searchInput = document.getElementById("search-input");

const categoryFilter = document.getElementById("category-filter");

const minPriceInput = document.getElementById("min-price");

const maxPriceInput = document.getElementById("max-price");

const ratingFilter = document.getElementById("rating-filter");

const stockFilter = document.getElementById("stock-filter");

const sortFilter = document.getElementById("sort-filter");

const productCount = document.getElementById("product-count");

const cartItems = document.getElementById("cart-items");

const cartCount = document.getElementById("cart-count");

const cartTotal = document.getElementById("cart-total");

const resetFiltersButton = document.getElementById("reset-filters");

const clearCartButton = document.getElementById("clear-cart");

What Is

getElementById()
document.getElementById()

is a DOM method that selects an HTML element using its ID.

For example:

const searchInput = document.getElementById("search-input");

Our HTML contains:

JavaScript finds that element and stores its reference inside the

searchInput

variable.

Now we can read its value and listen for user interactions.

7. Display Products Dynamically

We have product data, but we cannot see the products on the webpage yet.

We need to create a function that generates product cards.

function displayProducts(productArray) {

    productList.innerHTML = "";

    if (productArray.length === 0) {
        productList.innerHTML =
            'No products found.';

        return;
    }

    productArray.forEach(function(product) {

        const productCard = document.createElement("div");

        productCard.className = "product-card";

        const image = document.createElement("div");
        image.className = "product-image";
        image.textContent = product.image;

        const name = document.createElement("h3");
        name.textContent = product.name;

        const price = document.createElement("p");
        price.textContent = `Price: β‚Ή${product.price}`;

        const category = document.createElement("p");
        category.textContent = `Category: ${product.category}`;

        const rating = document.createElement("p");
        rating.textContent = `Rating: ⭐ ${product.rating}`;

        const stock = document.createElement("p");
        stock.textContent = product.inStock
            ? "In Stock"
            : "Out of Stock";

        const button = document.createElement("button");

        button.textContent = product.inStock
            ? "Add to Cart"
            : "Out of Stock";

        button.dataset.id = product.id;

        button.disabled = !product.inStock;

        productCard.append(
            image,
            name,
            price,
            category,
            rating,
            stock,
            button
        );

        productList.appendChild(productCard);

    });

    productCount.textContent =
        `${productArray.length} products found`;
}

Understanding

forEach()

The

forEach()

method runs a function once for every item in an array.

Example:

const numbers = [10, 20, 30];

numbers.forEach(function(number) {
    console.log(number);
});

Output:

10
20
30

In our project:

productArray.forEach(function(product) {
    // Create product card
});

JavaScript visits each product object and creates its product card.

Why Do We Use

innerHTML = ""

?

productList.innerHTML = "";

Every time we display products, we clear the previous product cards.

Otherwise, when we search or apply a filter, the old cards may remain and new cards may be added below them.

We want to replace the previous product list with the newly filtered result.

Why Do We Use

textContent

?

name.textContent = product.name;
textContent

inserts text into an element.

It is a safer choice when displaying dynamic text because it does not interpret the value as HTML.

8. Implement Product Search

Now let's implement the search functionality.

A customer should be able to type a product name and see matching results.

Add this function:

function searchProducts(productArray) {

    const searchTerm = searchInput.value.toLowerCase().trim();

    return productArray.filter(function(product) {

        return product.name
            .toLowerCase()
            .includes(searchTerm);

    });
}

Understanding the Search Logic

Suppose we have:

const productName = "Wireless Headphones";

const searchTerm = "wireless";

console.log(
    productName.toLowerCase().includes(searchTerm)
);

Output:

true

Why?

We use

filter()

For example, searching for

headphones

should return the Wireless Headphones product.

9. Implement Category Filtering

Now let's allow customers to filter products by category.

Add this function:

function filterByCategory(productArray) {

    const selectedCategory = categoryFilter.value;

    return productArray.filter(function(product) {

        if (selectedCategory === "all") {
            return true;
        }

        return product.category === selectedCategory;

    });
}

Understanding the Category Filter

Suppose a customer selects:

Electronics

Our JavaScript checks:

product.category === selectedCategory

If the product category is Electronics, the condition returns

true

If the category is Fashion, it returns

false

The

filter()

method returns only the products for which the callback returns

true

Why do we return

true

when the selected category is

"all"

?

Because the customer wants to see every product, regardless of category.

10. Implement Minimum and Maximum Price Filtering

A shopping website should allow customers to search within a price range.

For example:

Add this function:

function filterByPrice(productArray) {

    const minPrice = minPriceInput.value;

    const maxPrice = maxPriceInput.value;

    return productArray.filter(function(product) {

        const matchesMinPrice =
            minPrice === "" ||
            product.price >= Number(minPrice);

        const matchesMaxPrice =
            maxPrice === "" ||
            product.price <= Number(maxPrice);

        return matchesMinPrice && matchesMaxPrice;

    });
}

Understanding the Minimum Price Condition

minPrice === "" ||
product.price >= Number(minPrice)

This means:

Why do we use

Number()

?

Because input values are generally read as strings.

For example:

const price = "1000";

console.log(typeof price);

Output:

string

But product prices are numbers.

Therefore, we convert the input value:

Number(minPrice)

Understanding the Maximum Price Condition

product.price <= Number(maxPrice)

This checks whether the product price is less than or equal to the maximum price.

Why Do We Use

&&

?

return matchesMinPrice && matchesMaxPrice;

We want both conditions to be true.

A product must satisfy the minimum price and maximum price conditions to appear in the results.

11. Implement Rating Filtering

Customers often want products with good ratings.

Let's add a rating filter.

function filterByRating(productArray) {

    const minimumRating = Number(ratingFilter.value);

    return productArray.filter(function(product) {

        return product.rating >= minimumRating;

    });
}

Example

Suppose the customer selects:

4+ Stars

Our code checks:

product.rating >= 4

Products with ratings of 4, 4.2, 4.5, and 4.8 will be displayed.

Products with ratings below 4 will not be displayed.

If the customer selects All Ratings, the minimum rating is zero, so every product passes this condition.

12. Implement In-Stock Filtering

Sometimes products are unavailable.

We already have an

inStock

property in our product objects.

For example:

{
    id: 4,
    name: "Casual T-Shirt",
    price: 599,
    category: "Fashion",
    rating: 4.0,
    inStock: false,
    image: "πŸ‘•"
}

Now create this function:

function filterByStock(productArray) {

    const onlyInStock = stockFilter.checked;

    if (!onlyInStock) {
        return productArray;
    }

    return productArray.filter(function(product) {

        return product.inStock === true;

    });
}

Understanding Checkbox Values

For checkboxes, we use:

stockFilter.checked

It returns:

When the customer selects In-stock products only, we display products whose

inStock

value is

true

.

13. Combine All Filters into One Function

So far, we have created separate functions for:

But we need all filters to work together.

For example, a customer might:

  1. Search for Headphones.
  2. Select Electronics.
  3. Set a maximum price of β‚Ή2,000.
  4. Select a rating of 4+ stars.
  5. Select In-stock products only.

All these conditions should work together.

Create this function:

function filterProducts() {

    let filteredProducts = products;

    filteredProducts = searchProducts(filteredProducts);

    filteredProducts = filterByCategory(filteredProducts);

    filteredProducts = filterByPrice(filteredProducts);

    filteredProducts = filterByRating(filteredProducts);

    filteredProducts = filterByStock(filteredProducts);

    displayProducts(filteredProducts);
}

How Does This Function Work?

Initially:

let filteredProducts = products;

We start with the complete product array.

Then:

filteredProducts = searchProducts(filteredProducts);

Only products matching the search term remain.

Next:

filteredProducts = filterByCategory(filteredProducts);

We filter the remaining products by category.

The same process continues for price, rating, and stock.

This is important: every filter receives the result of the previous filter.

Example:

Suppose we have 12 products.

OperationExample resultAll products12Search Headphones1Category Electronics1Maximum price β‚Ή2,0001Rating 4+1In stock only1

The final result contains only products that satisfy every selected filter.

This is how multiple filters work together on a product listing page.

14. Implement Product Sorting

Filtering and sorting are different operations.

For example, a customer wants to see the cheapest products first.

Create this function:

function sortProducts(productArray) {

    const sortValue = sortFilter.value;

    const sortedProducts = [...productArray];

    if (sortValue === "price-low") {

        sortedProducts.sort(function(a, b) {
            return a.price - b.price;
        });

    } else if (sortValue === "price-high") {

        sortedProducts.sort(function(a, b) {
            return b.price - a.price;
        });

    } else if (sortValue === "rating-high") {

        sortedProducts.sort(function(a, b) {
            return b.rating - a.rating;
        });

    }

    return sortedProducts;
}

Understanding

sort()

The

sort()

method changes the order of array elements.

For numbers, we can use a comparison function.

Low to high:

products.sort(function(a, b) {
    return a.price - b.price;
});

If

a.price

is smaller than

b.price

, the result is negative, so

a

comes first.

High to low:

products.sort(function(a, b) {
    return b.price - a.price;
});

Now the higher-priced product comes first.

Why Do We Use

[...productArray]

?

const sortedProducts = [...productArray];

The spread operator creates a shallow copy of the array.

The

sort()

method modifies the original array. We do not want to change our original product data every time a customer selects a different sorting option.

Therefore, we sort a copy.

15. Update the Main Product Rendering Function

Now that we have created our filter and sorting functions, we need one function to run everything.

Add:

function updateProductPage() {

    let filteredProducts = products;

    filteredProducts = searchProducts(filteredProducts);

    filteredProducts = filterByCategory(filteredProducts);

    filteredProducts = filterByPrice(filteredProducts);

    filteredProducts = filterByRating(filteredProducts);

    filteredProducts = filterByStock(filteredProducts);

    const sortedProducts = sortProducts(filteredProducts);

    displayProducts(sortedProducts);
}

This is the main function responsible for updating the product listing.

Whenever a customer changes a filter or sorting option, we will call this function.

16. Add Event Listeners to Filters

We have created the filter functions, but how will JavaScript know when a customer changes a filter?

We use event listeners.

Add this code:

searchInput.addEventListener("input", updateProductPage);

categoryFilter.addEventListener("change", updateProductPage);

minPriceInput.addEventListener("input", updateProductPage);

maxPriceInput.addEventListener("input", updateProductPage);

ratingFilter.addEventListener("change", updateProductPage);

stockFilter.addEventListener("change", updateProductPage);

sortFilter.addEventListener("change", updateProductPage);

What Is an Event Listener?

An event listener waits for a particular action.

For example:

searchInput.addEventListener("input", updateProductPage);

This means whenever the customer types something in the search field, JavaScript calls

updateProductPage()

.

Common events used in this project:

EventWhen it runs

input

When the input value changes

change

When a select or checkbox value changes

click

When a button or element is clicked

17. Implement Reset Filters

Customers should be able to reset all filters and see every product again.

Add:

resetFiltersButton.addEventListener("click", function() {

    searchInput.value = "";

    categoryFilter.value = "all";

    minPriceInput.value = "";

    maxPriceInput.value = "";

    ratingFilter.value = "0";

    stockFilter.checked = false;

    sortFilter.value = "default";

    updateProductPage();

});

How Does Reset Work?

We are resetting every filter element to its default value.

For example:

searchInput.value = "";

Clears the search input.

categoryFilter.value = "all";

Selects All Categories.

stockFilter.checked = false;

Unchecks the stock checkbox.

Finally:

updateProductPage();

Refreshes the product listing using the default filter values.

18. Create the Shopping Cart Using JavaScript

Now let's implement the shopping cart.

We need an array to store the products added by the customer.

We will store each cart item using its product ID and quantity.

For example:

const cart = [
    {
        id: 1,
        quantity: 2
    },
    {
        id: 3,
        quantity: 1
    }
];

This means:

Why are we storing the ID instead of duplicating the entire product object?

Because our original

products

array already contains the product name, price, category, and other details.

We can use the ID to find the original product whenever we need its information.

19. Save Cart Data Using LocalStorage

Before adding products to the cart, let's understand LocalStorage.

What Is LocalStorage?

LocalStorage is a browser feature that allows websites to save small amounts of data as key-value pairs.

The data remains available even after the browser tab is closed or the page is refreshed, unless it is cleared by the user or browser.

Example:

localStorage.setItem("username", "Saif");

This saves a value with the key

username

.

To retrieve it:

const username = localStorage.getItem("username");

console.log(username);

Output:

Saif

To remove a value:

localStorage.removeItem("username");

To clear all LocalStorage data for the current website:

localStorage.clear();

Important: LocalStorage stores strings. It cannot directly store JavaScript arrays or objects.

That's why we use JSON.

What Is JSON.stringify()?

It converts JavaScript data into a JSON string.

const user = {
    name: "Saif",
    age: 27
};

const userString = JSON.stringify(user);

console.log(userString);

Output:

{"name":"Saif","age":27}

Now we can save this string:

localStorage.setItem("user", userString);

What Is JSON.parse()?

It converts a JSON string back into a JavaScript value.

const savedUser = localStorage.getItem("user");

const userObject = JSON.parse(savedUser);

console.log(userObject.name);

Output:

Saif

Remember:

MethodPurpose

JSON.stringify()

JavaScript value to JSON string

JSON.parse()

JSON string to JavaScript value

localStorage.setItem()

Save data

localStorage.getItem()

Read data

localStorage.removeItem()

Remove a stored key

20. Load Cart Data from LocalStorage

Now let's load previously saved cart data when the website opens.

Add:

let cart = [];

try {

    const savedCart = localStorage.getItem("shoppingCart");

    if (savedCart) {

        const parsedCart = JSON.parse(savedCart);

        if (Array.isArray(parsedCart)) {
            cart = parsedCart.filter(function(item) {

                const validProduct = products.some(function(product) {
                    return product.id === item.id;
                });

                return (
                    validProduct &&
                    Number.isInteger(item.quantity) &&
                    item.quantity > 0
                );

            });
        }

    }

} catch (error) {

    console.error("Unable to load cart:", error);

    cart = [];

}

Understanding This Code

First:

let cart = [];

We create an empty cart.

Then:

localStorage.getItem("shoppingCart");

We check whether a previously saved cart exists.

If it exists, we convert the JSON string back into JavaScript data:

JSON.parse(savedCart);

We also check that the saved value is an array and contains valid product IDs and positive integer quantities.

Why do we use

try...catch

Because LocalStorage data can be invalid or corrupted. If JSON parsing fails,

catch

prevents the entire JavaScript application from stopping.

21. Create a Function to Save the Cart

Now create a reusable function:

function saveCart() {

    localStorage.setItem(
        "shoppingCart",
        JSON.stringify(cart)
    );

}

Understanding the Function

JSON.stringify(cart)

Converts the cart array into a string.

localStorage.setItem("shoppingCart", ...);

Saves that string under the key

shoppingCart

.

Whenever we add, remove, or update a product quantity, we will call this function.

22. Implement Add to Cart

Now let's create the Add to Cart functionality.

function addToCart(productId) {

    const product = products.find(function(item) {
        return item.id === productId;
    });

    if (!product || !product.inStock) {
        return;
    }

    const existingItem = cart.find(function(item) {
        return item.id === productId;
    });

    if (existingItem) {

        existingItem.quantity++;

    } else {

        cart.push({
            id: productId,
            quantity: 1
        });

    }

    saveCart();

    displayCart();

}

Understanding

find()

The

find()

method returns the first array element that satisfies a condition.

Example:

const numbers = [10, 20, 30, 40];

const result = numbers.find(function(number) {
    return number > 20;
});

console.log(result);

Output:

30

In our project:

const product = products.find(function(item) {
    return item.id === productId;
});

We find the product whose ID matches the clicked product ID.

How Do We Prevent Duplicate Products?

Suppose a customer clicks Add to Cart twice for the same product.

We do not want two separate entries for that product.

Instead, we want:

[
    {
        id: 1,
        quantity: 2
    }
]

That's why we check:

const existingItem = cart.find(function(item) {
    return item.id === productId;
});

If the product already exists:

existingItem.quantity++;

We increase its quantity.

Otherwise:

cart.push({
    id: productId,
    quantity: 1
});

We add a new cart item.

This is how we prevent duplicate cart entries.

23. Connect Product Buttons Using Event Delegation

We need to detect which product's Add to Cart button was clicked.

We can use event delegation.

Add:

productList.addEventListener("click", function(event) {

    if (event.target.matches("button[data-id]")) {

        const productId = Number(event.target.dataset.id);

        addToCart(productId);

    }

});

What Is Event Delegation?

Instead of adding a separate click event listener to every product button, we add one listener to their parent container.

When a button is clicked, the click event bubbles up to

productList

.

Then we check:

event.target.matches("button[data-id]")

This confirms that the clicked element is a product button.

We retrieve its product ID using:

event.target.dataset.id

The

dataset

property allows JavaScript to read custom

data-*

HTML attributes.

For example:

Add to Cart

We convert the ID into a number because our product IDs are numbers.

24. Display Shopping Cart Items

Now we need to show the products inside the cart.

Create:

function displayCart() {

    cartItems.innerHTML = "";

    let totalItems = 0;

    if (cart.length === 0) {

        cartItems.innerHTML =
            'Your cart is empty.';

        cartCount.textContent = "0";

        cartTotal.textContent = "β‚Ή0";

        return;
    }

    let totalPrice = 0;

    cart.forEach(function(item) {

        const product = products.find(function(product) {
            return product.id === item.id;
        });

        if (!product) {
            return;
        }

        const itemTotal = product.price * item.quantity;

        totalPrice += itemTotal;

        totalItems += item.quantity;

        const cartItem = document.createElement("div");

        cartItem.className = "cart-item";

        const details = document.createElement("div");

        const name = document.createElement("h3");
        name.textContent = product.name;

        const price = document.createElement("p");
        price.textContent = `β‚Ή${product.price} Γ— ${item.quantity}`;

        details.append(name, price);

        const actions = document.createElement("div");

        actions.className = "cart-actions";

        const decreaseButton = document.createElement("button");
        decreaseButton.textContent = "-";
        decreaseButton.dataset.action = "decrease";
        decreaseButton.dataset.id = item.id;

        const quantity = document.createElement("span");
        quantity.textContent = item.quantity;

        const increaseButton = document.createElement("button");
        increaseButton.textContent = "+";
        increaseButton.dataset.action = "increase";
        increaseButton.dataset.id = item.id;

        const removeButton = document.createElement("button");
        removeButton.textContent = "Remove";
        removeButton.className = "remove-button";
        removeButton.dataset.action = "remove";
        removeButton.dataset.id = item.id;

        actions.append(
            decreaseButton,
            quantity,
            increaseButton,
            removeButton
        );

        cartItem.append(details, actions);

        cartItems.appendChild(cartItem);

    });

    cartCount.textContent = totalItems;

    cartTotal.textContent =
        `β‚Ή${totalPrice.toLocaleString("en-IN")}`;

}

Understanding Cart Total

Suppose a customer adds:

ProductPriceQuantityTotalHeadphonesβ‚Ή1,4992β‚Ή2,998Running Shoesβ‚Ή1,9991β‚Ή1,999

The total is:

2998 + 1999 = 4997

Our code calculates the total using:

const itemTotal = product.price * item.quantity;

totalPrice += itemTotal;

For each cart item, we multiply its price by its quantity and add the result to

totalPrice

.

We also calculate the total number of items:

totalItems += item.quantity;

This is why the cart indicator displays the total quantity rather than the number of different product types.

25. Increase and Decrease Product Quantity

Now let's implement the plus and minus buttons.

function increaseQuantity(productId) {

    const item = cart.find(function(item) {
        return item.id === productId;
    });

    if (!item) {
        return;
    }

    item.quantity++;

    saveCart();

    displayCart();

}

When the customer clicks the plus button, we find the matching cart item and increase its quantity.

Now the decrease function:

function decreaseQuantity(productId) {

    const item = cart.find(function(item) {
        return item.id === productId;
    });

    if (!item) {
        return;
    }

    item.quantity--;

    if (item.quantity <= 0) {

        removeFromCart(productId);

        return;
    }

    saveCart();

    displayCart();

}

If the quantity becomes zero, we remove the product from the cart.

Why?

Because a shopping cart should not contain products with zero quantity.

26. Remove Product from Cart

Create:

function removeFromCart(productId) {

    cart = cart.filter(function(item) {

        return item.id !== productId;

    });

    saveCart();

    displayCart();

}

Understanding the Logic

Suppose our cart contains:

[
    { id: 1, quantity: 2 },
    { id: 3, quantity: 1 },
    { id: 5, quantity: 1 }
]

We want to remove product ID 3.

Our condition is:

item.id !== productId

This means we keep all items except the product whose ID matches the selected product ID.

The

filter()

method returns a new array without that item.

27. Handle Cart Button Clicks

Now we need to connect the cart buttons with their functions.

Add:

cartItems.addEventListener("click", function(event) {

    const button = event.target.closest("button[data-action]");

    if (!button) {
        return;
    }

    const productId = Number(button.dataset.id);

    const action = button.dataset.action;

    if (action === "increase") {

        increaseQuantity(productId);

    } else if (action === "decrease") {

        decreaseQuantity(productId);

    } else if (action === "remove") {

        removeFromCart(productId);

    }

});

Why Do We Use

closest()

?

event.target.closest("button[data-action]")

It finds the closest matching button starting from the clicked element.

This is useful when the button contains nested elements.

We then read:

button.dataset.action

It tells us whether the customer clicked:

Based on that value, we call the correct function.

28. Implement Clear Cart

Sometimes a customer wants to remove everything from the cart.

Add:

clearCartButton.addEventListener("click", function() {

    cart = [];

    saveCart();

    displayCart();

});

How Does It Work?

cart = [];

Replaces the existing cart with an empty array.

saveCart();

Updates LocalStorage.

displayCart();

Refreshes the cart display.

Now the cart will show the empty-cart message.

29. Initialize the Product Page

We have created all the main functions.

But we still need to display products and restore the cart when the page first opens.

Add this at the bottom of

script.js

:

updateProductPage();

displayCart();

The first function displays the products using the current filter values.

The second function displays any cart data loaded from LocalStorage.

Without these calls, the functions would exist, but the page would not automatically render the products and cart on initial load.

30. Complete JavaScript Code

Here is the complete

script.js

file in one place.

If you followed the steps above, you have already written each part. This combined version is useful when you want to check your code or build the project from scratch.

// ===================================
// 1. PRODUCT DATA
// ===================================

const products = [
    { id: 1, name: "Wireless Headphones", price: 1499, category: "Electronics", rating: 4.5, inStock: true, image: "🎧" },
    { id: 2, name: "Smart Watch", price: 2499, category: "Electronics", rating: 4.2, inStock: true, image: "⌚" },
    { id: 3, name: "Running Shoes", price: 1999, category: "Fashion", rating: 4.7, inStock: true, image: "πŸ‘Ÿ" },
    { id: 4, name: "Casual T-Shirt", price: 599, category: "Fashion", rating: 4.0, inStock: false, image: "πŸ‘•" },
    { id: 5, name: "Laptop", price: 45999, category: "Electronics", rating: 4.8, inStock: true, image: "πŸ’»" },
    { id: 6, name: "Backpack", price: 1299, category: "Accessories", rating: 4.1, inStock: true, image: "πŸŽ’" },
    { id: 7, name: "Sunglasses", price: 899, category: "Accessories", rating: 3.9, inStock: true, image: "πŸ•ΆοΈ" },
    { id: 8, name: "Bluetooth Speaker", price: 1799, category: "Electronics", rating: 4.3, inStock: false, image: "πŸ”Š" },
    { id: 9, name: "Denim Jacket", price: 2299, category: "Fashion", rating: 4.6, inStock: true, image: "πŸ§₯" },
    { id: 10, name: "Leather Wallet", price: 799, category: "Accessories", rating: 4.4, inStock: true, image: "πŸ‘›" },
    { id: 11, name: "Gaming Mouse", price: 999, category: "Electronics", rating: 4.5, inStock: true, image: "πŸ–±οΈ" },
    { id: 12, name: "Sports Cap", price: 499, category: "Fashion", rating: 3.8, inStock: true, image: "🧒" }
];

// ===================================
// 2. SELECT HTML ELEMENTS
// ===================================

const productList = document.getElementById("product-list");
const searchInput = document.getElementById("search-input");
const categoryFilter = document.getElementById("category-filter");
const minPriceInput = document.getElementById("min-price");
const maxPriceInput = document.getElementById("max-price");
const ratingFilter = document.getElementById("rating-filter");
const stockFilter = document.getElementById("stock-filter");
const sortFilter = document.getElementById("sort-filter");
const productCount = document.getElementById("product-count");

const cartItems = document.getElementById("cart-items");
const cartCount = document.getElementById("cart-count");
const cartTotal = document.getElementById("cart-total");

const resetFiltersButton = document.getElementById("reset-filters");
const clearCartButton = document.getElementById("clear-cart");

// ===================================
// 3. LOAD CART FROM LOCALSTORAGE
// ===================================

let cart = [];

try {

    const savedCart = localStorage.getItem("shoppingCart");

    if (savedCart) {

        const parsedCart = JSON.parse(savedCart);

        if (Array.isArray(parsedCart)) {

            cart = parsedCart.filter(function(item) {

                const validProduct = products.some(function(product) {
                    return product.id === item.id;
                });

                return (
                    validProduct &&
                    Number.isInteger(item.quantity) &&
                    item.quantity > 0
                );

            });

        }

    }

} catch (error) {

    console.error("Unable to load cart:", error);

    cart = [];

}

// ===================================
// 4. DISPLAY PRODUCTS
// ===================================

function displayProducts(productArray) {

    productList.innerHTML = "";

    if (productArray.length === 0) {

        productList.innerHTML =
            'No products found.';

        productCount.textContent = "0 products found";

        return;
    }

    productArray.forEach(function(product) {

        const card = document.createElement("div");
        card.className = "product-card";

        const image = document.createElement("div");
        image.className = "product-image";
        image.textContent = product.image;

        const name = document.createElement("h3");
        name.textContent = product.name;

        const price = document.createElement("p");
        price.textContent = `Price: β‚Ή${product.price}`;

        const category = document.createElement("p");
        category.textContent = `Category: ${product.category}`;

        const rating = document.createElement("p");
        rating.textContent = `Rating: ⭐ ${product.rating}`;

        const stock = document.createElement("p");
        stock.textContent = product.inStock
            ? "In Stock"
            : "Out of Stock";

        const button = document.createElement("button");

        button.textContent = product.inStock
            ? "Add to Cart"
            : "Out of Stock";

        button.dataset.id = product.id;
        button.disabled = !product.inStock;

        card.append(
            image,
            name,
            price,
            category,
            rating,
            stock,
            button
        );

        productList.appendChild(card);

    });

    productCount.textContent =
        `${productArray.length} products found`;

}

// ===================================
// 5. SEARCH PRODUCTS
// ===================================

function searchProducts(productArray) {

    const searchTerm = searchInput.value.toLowerCase().trim();

    return productArray.filter(function(product) {

        return product.name
            .toLowerCase()
            .includes(searchTerm);

    });

}

// ===================================
// 6. CATEGORY FILTER
// ===================================

function filterByCategory(productArray) {

    const selectedCategory = categoryFilter.value;

    return productArray.filter(function(product) {

        if (selectedCategory === "all") {
            return true;
        }

        return product.category === selectedCategory;

    });

}

// ===================================
// 7. PRICE FILTER
// ===================================

function filterByPrice(productArray) {

    const minPrice = minPriceInput.value;
    const maxPrice = maxPriceInput.value;

    return productArray.filter(function(product) {

        const matchesMinPrice =
            minPrice === "" ||
            product.price >= Number(minPrice);

        const matchesMaxPrice =
            maxPrice === "" ||
            product.price <= Number(maxPrice);

        return matchesMinPrice && matchesMaxPrice;

    });

}

// ===================================
// 8. RATING FILTER
// ===================================

function filterByRating(productArray) {

    const minimumRating = Number(ratingFilter.value);

    return productArray.filter(function(product) {

        return product.rating >= minimumRating;

    });

}

// ===================================
// 9. STOCK FILTER
// ===================================

function filterByStock(productArray) {

    const onlyInStock = stockFilter.checked;

    if (!onlyInStock) {
        return productArray;
    }

    return productArray.filter(function(product) {

        return product.inStock === true;

    });

}

// ===================================
// 10. SORT PRODUCTS
// ===================================

function sortProducts(productArray) {

    const sortValue = sortFilter.value;

    const sortedProducts = [...productArray];

    if (sortValue === "price-low") {

        sortedProducts.sort(function(a, b) {
            return a.price - b.price;
        });

    } else if (sortValue === "price-high") {

        sortedProducts.sort(function(a, b) {
            return b.price - a.price;
        });

    } else if (sortValue === "rating-high") {

        sortedProducts.sort(function(a, b) {
            return b.rating - a.rating;
        });

    }

    return sortedProducts;

}

// ===================================
// 11. UPDATE PRODUCT PAGE
// ===================================

function updateProductPage() {

    let filteredProducts = products;

    filteredProducts = searchProducts(filteredProducts);
    filteredProducts = filterByCategory(filteredProducts);
    filteredProducts = filterByPrice(filteredProducts);
    filteredProducts = filterByRating(filteredProducts);
    filteredProducts = filterByStock(filteredProducts);

    const sortedProducts = sortProducts(filteredProducts);

    displayProducts(sortedProducts);

}

// ===================================
// 12. RESET FILTERS
// ===================================

resetFiltersButton.addEventListener("click", function() {

    searchInput.value = "";
    categoryFilter.value = "all";
    minPriceInput.value = "";
    maxPriceInput.value = "";
    ratingFilter.value = "0";
    stockFilter.checked = false;
    sortFilter.value = "default";

    updateProductPage();

});

// ===================================
// 13. FILTER EVENT LISTENERS
// ===================================

searchInput.addEventListener("input", updateProductPage);
categoryFilter.addEventListener("change", updateProductPage);
minPriceInput.addEventListener("input", updateProductPage);
maxPriceInput.addEventListener("input", updateProductPage);
ratingFilter.addEventListener("change", updateProductPage);
stockFilter.addEventListener("change", updateProductPage);
sortFilter.addEventListener("change", updateProductPage);

// ===================================
// 14. SAVE CART
// ===================================

function saveCart() {

    localStorage.setItem(
        "shoppingCart",
        JSON.stringify(cart)
    );

}

// ===================================
// 15. ADD TO CART
// ===================================

function addToCart(productId) {

    const product = products.find(function(item) {
        return item.id === productId;
    });

    if (!product || !product.inStock) {
        return;
    }

    const existingItem = cart.find(function(item) {
        return item.id === productId;
    });

    if (existingItem) {

        existingItem.quantity++;

    } else {

        cart.push({
            id: productId,
            quantity: 1
        });

    }

    saveCart();
    displayCart();

}

// ===================================
// 16. PRODUCT BUTTON EVENT
// ===================================

productList.addEventListener("click", function(event) {

    if (event.target.matches("button[data-id]")) {

        const productId = Number(event.target.dataset.id);

        addToCart(productId);

    }

});

// ===================================
// 17. DISPLAY CART
// ===================================

function displayCart() {

    cartItems.innerHTML = "";

    let totalItems = 0;
    let totalPrice = 0;

    if (cart.length === 0) {

        cartItems.innerHTML =
            'Your cart is empty.';

        cartCount.textContent = "0";
        cartTotal.textContent = "β‚Ή0";

        return;
    }

    cart.forEach(function(item) {

        const product = products.find(function(product) {
            return product.id === item.id;
        });

        if (!product) {
            return;
        }

        const itemTotal = product.price * item.quantity;

        totalPrice += itemTotal;
        totalItems += item.quantity;

        const cartItem = document.createElement("div");
        cartItem.className = "cart-item";

        const details = document.createElement("div");

        const name = document.createElement("h3");
        name.textContent = product.name;

        const price = document.createElement("p");
        price.textContent = `β‚Ή${product.price} Γ— ${item.quantity}`;

        details.append(name, price);

        const actions = document.createElement("div");
        actions.className = "cart-actions";

        const decreaseButton = document.createElement("button");
        decreaseButton.textContent = "-";
        decreaseButton.dataset.action = "decrease";
        decreaseButton.dataset.id = item.id;

        const quantity = document.createElement("span");
        quantity.textContent = item.quantity;

        const increaseButton = document.createElement("button");
        increaseButton.textContent = "+";
        increaseButton.dataset.action = "increase";
        increaseButton.dataset.id = item.id;

        const removeButton = document.createElement("button");
        removeButton.textContent = "Remove";
        removeButton.className = "remove-button";
        removeButton.dataset.action = "remove";
        removeButton.dataset.id = item.id;

        actions.append(
            decreaseButton,
            quantity,
            increaseButton,
            removeButton
        );

        cartItem.append(details, actions);

        cartItems.appendChild(cartItem);

    });

    cartCount.textContent = totalItems;

    cartTotal.textContent =
        `β‚Ή${totalPrice.toLocaleString("en-IN")}`;

}

// ===================================
// 18. QUANTITY FUNCTIONS
// ===================================

function increaseQuantity(productId) {

    const item = cart.find(function(item) {
        return item.id === productId;
    });

    if (!item) {
        return;
    }

    item.quantity++;

    saveCart();
    displayCart();

}

function decreaseQuantity(productId) {

    const item = cart.find(function(item) {
        return item.id === productId;
    });

    if (!item) {
        return;
    }

    item.quantity--;

    if (item.quantity <= 0) {

        removeFromCart(productId);

        return;
    }

    saveCart();
    displayCart();

}

// ===================================
// 19. REMOVE FROM CART
// ===================================

function removeFromCart(productId) {

    cart = cart.filter(function(item) {

        return item.id !== productId;

    });

    saveCart();
    displayCart();

}

// ===================================
// 20. CART BUTTON EVENTS
// ===================================

cartItems.addEventListener("click", function(event) {

    const button = event.target.closest("button[data-action]");

    if (!button) {
        return;
    }

    const productId = Number(button.dataset.id);

    const action = button.dataset.action;

    if (action === "increase") {

        increaseQuantity(productId);

    } else if (action === "decrease") {

        decreaseQuantity(productId);

    } else if (action === "remove") {

        removeFromCart(productId);

    }

});

// ===================================
// 21. CLEAR CART
// ===================================

clearCartButton.addEventListener("click", function() {

    cart = [];

    saveCart();
    displayCart();

});

// ===================================
// 22. INITIAL PAGE LOAD
// ===================================

updateProductPage();

displayCart();

31. How to Test the Project

After writing all three files, open

index.html

in your browser.

Follow these steps to test the functionality.

TestExpected resultOpen the pageAll 12 products appearSearch for LaptopOnly Laptop appearsSelect ElectronicsOnly electronics appearSet minimum price to 1,000Cheaper products disappearSet maximum price to 2,000More expensive products disappearSelect 4+ StarsProducts below 4 stars disappearEnable In-stock onlyOut-of-stock products disappearSelect Price: Low to HighCheapest products appear firstClick Add to Cart twiceOne cart entry with quantity 2Click +Quantity increasesClick -Quantity decreasesClick RemoveProduct disappears from cartRefresh the pageCart data remainsClick Clear CartCart becomes emptyClick Reset FiltersAll products appear again

32. Important Things to Understand About LocalStorage

LocalStorage is useful for learning and building small frontend projects, but it has limitations.

1. LocalStorage is browser-specific

If a customer adds a product on one browser, the same cart will not automatically appear on another browser or device.

2. LocalStorage is not a database

It stores data inside the browser. It does not automatically synchronize with a server.

3. Users can modify LocalStorage

A user can open browser developer tools and change stored values.

Therefore, a real e-commerce application must never trust LocalStorage for product prices, inventory, discounts, or payments.

4. Real applications need backend validation

In a production application:

LocalStorage is suitable for a frontend learning project and can be used for a guest cart, but it is not a secure order system.

33. Common Mistakes Beginners Make

Mistake 1: Forgetting JSON.stringify()

Incorrect:

localStorage.setItem("cart", cart);

Correct:

localStorage.setItem("cart", JSON.stringify(cart));

Why? LocalStorage stores strings, so we convert the array into a JSON string first.

Mistake 2: Forgetting JSON.parse()

Incorrect:

const cart = localStorage.getItem("cart");

This returns a string, not a JavaScript array.

Correct:

const cart = JSON.parse(localStorage.getItem("cart"));

Remember to handle the case where the key is missing or the saved JSON is invalid.

Mistake 3: Using

=

Instead of

===

Incorrect:

product.category = selectedCategory;

Correct:

product.category === selectedCategory;

The first statement assigns a value. The second compares two values.

Mistake 4: Sorting the Original Product Array

Potentially problematic:

products.sort(function(a, b) {
    return a.price - b.price;
});

Better:

const sortedProducts = [...products];

sortedProducts.sort(function(a, b) {
    return a.price - b.price;
});

This avoids changing the original array order.

Mistake 5: Not Updating LocalStorage

If you change the cart but do not call

saveCart()

, the latest cart data will not be saved.

Call it after every cart operation.

34. Practice Exercises for Students

Now that you have built the project, try improving it yourself.

Beginner Level

  1. Add five more products.
  2. Add a new category called Home Appliances.
  3. Add a product description.
  4. Display the total number of different products in the cart.
  5. Show an alert when a product is added to the cart.

Intermediate Level

  1. Add a discount percentage to each product.
  2. Display the original price and discounted price.
  3. Add sorting by product name.
  4. Add a filter for products above β‚Ή5,000.
  5. Add a button to remove all filters except the search term.
  6. Display a message when a product is successfully added to the cart.

Advanced Level

  1. Create a separate product details page.
  2. Add a wishlist feature using LocalStorage.
  3. Add pagination to display products in groups.
  4. Add a cart badge that updates without reloading the page.
  5. Add a checkout form.
  6. Connect the frontend to a Node.js and Express backend.
  7. Store products and orders in MongoDB or PostgreSQL.
  8. Add user authentication and save carts to the database.

35. Interview Questions Based on This Project

Q1. What is LocalStorage in JavaScript?

LocalStorage is a browser storage mechanism that allows us to store key-value data as strings. The stored data remains available across page refreshes and browser sessions until it is removed.

Q2. What is the difference between LocalStorage and SessionStorage?

LocalStorage persists until data is removed. SessionStorage is generally limited to the current browser tab session and is cleared when that tab's session ends.

Q3. Why do we use JSON.stringify()?

We use

JSON.stringify()

to convert JavaScript objects or arrays into strings before saving them in LocalStorage.

Q4. Why do we use JSON.parse()?

We use

JSON.parse()

Q5. What is the difference between

filter()

and

find()
filter()

returns a new array containing all matching elements.

find()

returns the first matching element or

undefined

Q6. What is the difference between

map()

and

forEach()
map()

creates and returns a new array containing transformed values.

forEach()

executes a callback for each array item and does not create a new result array.

Q7. Why do we use the spread operator before sorting?

The spread operator creates a shallow copy of an array. We use it because

sort()

modifies the original array.

Q8. How do you prevent duplicate products in a cart?

We use

find()

to check whether a product ID already exists in the cart. If it exists, we increase its quantity instead of adding another entry.

Q9. Why should we not trust prices stored in LocalStorage?

Users can modify browser storage. A backend must validate product prices and calculate the final order amount before accepting an order.

Q10. What is event delegation?

Event delegation is a technique where we attach an event listener to a parent element and handle events from its child elements using event bubbling.

36. Related JavaScript Projects to Learn Next

After completing this e-commerce project, you can build these projects to improve your JavaScript skills.

  1. JavaScript Shopping Cart Project: Build a dedicated cart page with quantity management, subtotal, tax, and discounts.
  2. JavaScript Wishlist Project: Allow customers to save their favourite products using LocalStorage.
  3. JavaScript Product Details Page: Display product images, descriptions, ratings, and available variations.
  4. JavaScript Checkout Page: Create an address form, order summary, and checkout validation.
  5. JavaScript Todo Application: Learn CRUD operations, DOM manipulation, and LocalStorage.
  6. JavaScript Expense Tracker: Add expenses, categories, filters, and total calculations.
  7. JavaScript Weather Application: Learn how to fetch and display data from an API.
  8. MERN Stack E-commerce Application: Convert this frontend project into a full-stack application using React, Node.js, Express, and MongoDB.

37. Conclusion

In this project, we built a practical JavaScript e-commerce product page with multiple features.

We learned how to:

The most important lesson is that JavaScript becomes easier to understand when you use its concepts to solve real problems.

Don't just copy the code. Try changing the product data, adding new filters, and building additional features. This is how you develop practical JavaScript skills.

SEO Details for SamWithCode

SEO Title:

JavaScript E-commerce Product Page Project – Search, Filter, Sort & Add to Cart

Meta Description:

Build a complete e-commerce product page using HTML, CSS, and JavaScript. Learn product search, category filters, price range, sorting, ratings, Add to Cart, quantity management, and LocalStorage with complete source code.

URL Slug:

javascript-ecommerce-product-page-project

Primary Focus Keyword:

JavaScript E-commerce Project

Secondary Keywords:

Suggested Blog Category:

JavaScript Projects

Suggested Tags:

JavaScript, HTML, CSS, E-commerce Project, Add to Cart, LocalStorage, DOM Manipulation, JavaScript Projects, Shopping Cart

Suggested Featured Image Text:

JavaScript E-commerce Product Page

Search | Filter | Sort | Add to Cart | LocalStorage

Suggested Internal Links:

Link this article to your related SamWithCode tutorials:

Suggested Next Blog:

Build a Complete JavaScript Shopping Cart Page – Quantity, Discount, Tax & Checkout