Shopping Cart with LocalStorage: Save Cart Items (Beginner Guide)

Shopping Cart with LocalStorage: Save Cart Items (Beginner Guide)


Shopping Cart with LocalStorage: Save Cart Items (Beginner Guide)


Learn how to build a shopping cart that remembers products even after the user refreshes the page using JavaScript LocalStorage.


Introduction

Imagine adding products to an online shopping cart and then accidentally refreshing the page.

Without data persistence, every selected item disappears instantly.

That would create a frustrating user experience.

Modern e-commerce websites solve this problem using storage technologies that keep data available even after page reloads.

One of the easiest storage solutions available in JavaScript is LocalStorage.

In this project, you'll learn how to create a shopping cart that saves products inside the browser and restores them automatically whenever the page loads.

This is one of the most practical beginner JavaScript projects because it combines DOM manipulation, arrays, events, JSON, and browser storage.


What Is LocalStorage?

What It Is

LocalStorage is a browser feature that allows websites to store data permanently inside the user's browser.

Unlike variables, LocalStorage data remains available even after refreshing or closing the browser.

Why It Matters

Without LocalStorage, cart items would disappear every time the page reloads.

Real-World Examples

  • Shopping Carts
  • Dark Mode Preferences
  • User Settings
  • Language Preferences
  • Recently Viewed Products

How LocalStorage Works

LocalStorage stores information as key-value pairs.

Save Data

localStorage.setItem(

"name",

"John"

);

Read Data

localStorage.getItem(

"name"

);

Delete Data

localStorage.removeItem(

"name"

);

Clear Everything

localStorage.clear();

Project Overview

Our shopping cart will include:

  • Add Product Button
  • Cart Item List
  • Save Cart to LocalStorage
  • Load Cart Automatically
  • Remove Items
  • Clear Entire Cart

This mirrors the behavior of many real-world e-commerce websites.


Creating the HTML Structure

Product Section

Laptop

Why It Matters

Users need a way to add products and view their cart contents.


Creating the Cart Array

What It Is

The cart array stores selected products.

JavaScript

let cart = [];

Why It Matters

Arrays allow us to manage multiple products efficiently.


Adding Products to the Cart

JavaScript

document.getElementById(

"addBtn"

).addEventListener(

"click",

function(){

 cart.push(

  "Laptop"

 );

 console.log(cart);

}

);

Result

Every click adds a new product to the cart array.

Real-World Example

Amazon, Flipkart, and Shopify stores perform similar actions whenever users add products to their carts.


Displaying Cart Items on the Page

What It Is

Users should see their selected products immediately.

JavaScript

const cartList =

document.getElementById(

"cart"

);

cartList.innerHTML = "";

We'll expand this display system in the next section.


Why This Project Is Great for Beginners

This project teaches several essential JavaScript concepts:

  • Arrays
  • DOM Manipulation
  • Events
  • LocalStorage
  • JSON
  • User Interaction

These concepts appear frequently in real frontend applications and help build a strong JavaScript foundation.


Rendering Cart Items on the Screen

What It Is

Adding products to an array is useful, but users also need to see their cart visually.

We can create a function that displays all cart items inside the webpage.

JavaScript

const cartList =

document.getElementById(

"cart"

);

function renderCart(){

 cartList.innerHTML = "";

 cart.forEach(function(item){

  cartList.innerHTML +=

  `
  • ${item}
  • `; }); }

    Why It Matters

    Whenever the cart changes, the UI updates automatically.


    Updating the Cart After Adding Products

    JavaScript

    document.getElementById(
    
    "addBtn"
    
    ).addEventListener(
    
    "click",
    
    function(){
    
     cart.push(
    
      "Laptop"
    
     );
    
     renderCart();
    
    }
    
    );
    

    Result

    Products now appear instantly after being added.

    Real-World Example

    Shopping websites update cart contents immediately when products are selected.


    Saving Cart Data to LocalStorage

    What It Is

    Currently, refreshing the page still removes all products.

    To make the cart persistent, we need to save it inside LocalStorage.

    JavaScript

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

    Why It Matters

    LocalStorage can only store strings.

    JSON.stringify() converts arrays into strings before saving.


    Saving Automatically After Every Change

    Improved Example

    document.getElementById(
    
    "addBtn"
    
    ).addEventListener(
    
    "click",
    
    function(){
    
     cart.push(
    
      "Laptop"
    
     );
    
     localStorage.setItem(
    
      "cart",
    
      JSON.stringify(cart)
    
     );
    
     renderCart();
    
    }
    
    );
    

    Result

    Every product addition is immediately saved.


    Loading Cart Data from LocalStorage

    What It Is

    Saving data is only half the solution.

    We also need to load saved data whenever the page opens.

    JavaScript

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

    Why It Matters

    This retrieves previously stored cart information.


    Converting JSON Back Into an Array

    What It Is

    Data retrieved from LocalStorage is still a string.

    We must convert it back into an array.

    JavaScript

    cart = JSON.parse(
    
    savedCart
    
    );
    

    Why It Matters

    JSON.parse() transforms JSON strings back into usable JavaScript objects and arrays.


    Loading Saved Products Automatically

    JavaScript

    const savedCart =
    
    localStorage.getItem(
    
    "cart"
    
    );
    
    if(savedCart){
    
     cart = JSON.parse(
    
      savedCart
    
     );
    
     renderCart();
    
    }
    

    Result

    Previously saved products appear automatically after refreshing the page.

    Real-World Example

    Most e-commerce platforms restore cart contents when users return later.


    Understanding JSON.stringify()

    What It Is

    JSON.stringify() converts JavaScript objects and arrays into strings.

    Example

    const products =
    
    ["Laptop","Phone"];
    
    JSON.stringify(products);
    

    Output

    ["Laptop","Phone"]
    

    Why It Matters

    Without JSON.stringify(), LocalStorage cannot properly save arrays.


    Understanding JSON.parse()

    What It Is

    JSON.parse() performs the opposite operation.

    It converts strings back into JavaScript arrays or objects.

    Example

    JSON.parse(
    
    '["Laptop","Phone"]'
    
    );
    

    Result

    JavaScript receives a usable array again.


    Common LocalStorage Mistakes

    • Forgetting JSON.stringify()
    • Forgetting JSON.parse()
    • Saving too much data
    • Using incorrect storage keys
    • Not checking for existing data

    Most Common Error

    Beginners often save arrays directly without converting them to JSON.

    This leads to unexpected behavior when reading data later.


    Professional Best Practices

    • Use Consistent Storage Keys
    • Always Validate Stored Data
    • Handle Missing Data Safely
    • Keep Storage Organized
    • Use JSON for Complex Data
    • Update Storage After Every Change

    Professional applications carefully manage LocalStorage to ensure data remains reliable and consistent.


    Removing Items from the Cart

    What It Is

    A shopping cart should allow users to remove products they no longer want.

    Why It Matters

    Users often change their minds before purchasing.

    Providing a remove option improves usability and creates a better shopping experience.

    JavaScript Example

    cart.splice(
    
    index,
    
    1
    
    );
    
    localStorage.setItem(
    
    "cart",
    
    JSON.stringify(cart)
    
    );
    
    renderCart();
    

    How It Works

    splice() removes an item from the array.

    The updated cart is then saved back into LocalStorage.


    Adding Remove Buttons

    Goal

    Display a remove button next to every cart item.

    JavaScript

    function renderCart(){
    
     cartList.innerHTML = "";
    
     cart.forEach(function(
    
      item,
    
      index
    
     ){
    
      cartList.innerHTML +=
    
      `
      
  • ${item}
  • `; }); }

    Result

    Every product now has its own remove button.


    Creating the removeItem() Function

    JavaScript

    function removeItem(
    
    index
    
    ){
    
     cart.splice(
    
      index,
    
      1
    
     );
    
     localStorage.setItem(
    
      "cart",
    
      JSON.stringify(cart)
    
     );
    
     renderCart();
    
    }
    

    Result

    Products disappear instantly from both the page and LocalStorage.


    Clearing the Entire Cart

    What It Is

    Many users prefer a single button that removes everything at once.

    HTML

    
    

    JavaScript

    document.getElementById(
    
    "clearCart"
    
    ).addEventListener(
    
    "click",
    
    function(){
    
     cart = [];
    
     localStorage.removeItem(
    
      "cart"
    
     );
    
     renderCart();
    
    }
    
    );
    

    Why It Matters

    This gives users full control over their cart.


    Building the Complete Shopping Cart Project

    Features Included

    • Add Products
    • Display Products
    • Save to LocalStorage
    • Load Automatically
    • Remove Products
    • Clear Entire Cart

    Workflow

    Add Product
    
    ↓
    
    Update Array
    
    ↓
    
    Save To LocalStorage
    
    ↓
    
    Refresh UI
    
    ↓
    
    Data Persists
    

    Why It Matters

    This mirrors the basic behavior of real e-commerce shopping carts.


    Where LocalStorage Shopping Carts Are Used

    LocalStorage is commonly used for temporary cart storage in many applications.

    • E-commerce Websites
    • Online Food Ordering Apps
    • Course Marketplaces
    • Digital Product Stores
    • Event Ticket Platforms
    • Subscription Services
    • Booking Systems
    • Small Business Websites
    • Portfolio Stores
    • Demo Projects

    Even large applications often use LocalStorage alongside backend storage systems.


    Limitations of LocalStorage

    What It Is

    While LocalStorage is useful, it is not perfect.

    Limitations

    • Browser Storage Only
    • Not Shared Across Devices
    • Limited Storage Size
    • Can Be Cleared by Users
    • Not Suitable for Sensitive Data

    Professional Insight

    Production applications often synchronize LocalStorage data with a backend database.


    Shopping Cart + LocalStorage Cheat Sheet

    Task Code
    Save Data localStorage.setItem()
    Read Data localStorage.getItem()
    Delete One Item removeItem()
    Delete All Data clear()
    Convert Array to JSON JSON.stringify()
    Convert JSON to Array JSON.parse()
    Remove Array Item splice()

    JavaScript LocalStorage Interview Questions

    • What is LocalStorage?
    • How is LocalStorage different from Session Storage?
    • Why does LocalStorage store only strings?
    • What does JSON.stringify() do?
    • What does JSON.parse() do?
    • How do you save arrays in LocalStorage?
    • How do you remove stored data?
    • What are the limitations of LocalStorage?
    • Why is LocalStorage useful for shopping carts?
    • When should backend storage be used instead?

    Frequently Asked Questions

    Does LocalStorage survive page refreshes?

    Yes. Data remains available even after refreshing or closing the browser.

    Can LocalStorage store arrays?

    Not directly. Arrays must first be converted using JSON.stringify().

    Can users delete LocalStorage data?

    Yes. Browser settings or cache clearing can remove LocalStorage data.

    Should passwords be stored in LocalStorage?

    No. Sensitive information should never be stored in LocalStorage.

    What is the most common beginner mistake?

    Forgetting to use JSON.stringify() and JSON.parse() when working with arrays.

    Is LocalStorage enough for a real e-commerce website?

    Usually not. Real stores often combine LocalStorage with backend databases and user accounts.


    Why This Project Matters

    The Shopping Cart with LocalStorage project is one of the best beginner JavaScript projects because it introduces concepts used in real-world applications.

    You'll learn how to store data, retrieve data, update the DOM, manage arrays, and create persistent user experiences.

    These same concepts appear in dashboards, productivity apps, user settings pages, and modern frontend frameworks.

    Mastering this project gives you practical experience with one of the most useful browser APIs available today.


    Conclusion

    Building a Shopping Cart with LocalStorage teaches essential JavaScript skills while solving a real-world problem.

    By combining arrays, DOM manipulation, LocalStorage, JSON methods, and event handling, you can create an application that remembers user selections even after page refreshes.

    The most important concepts from this guide are:

    • LocalStorage
    • JSON.stringify()
    • JSON.parse()
    • Arrays
    • DOM Manipulation
    • Event Handling
    • Cart Rendering
    • Removing Items
    • Persistent Data Storage

    Master these concepts and you'll be ready to build more advanced JavaScript applications such as wishlists, task managers, note-taking apps, and complete e-commerce experiences.

    Comments

    Popular posts from this blog

    My JavaScript Learning Journey: Roadmap Recap, Best Topics & Job Ready Checklist

    JavaScript 2-Week Roadmap for Beginners: Learn JS Step-by-Step in 14 Days

    JavaScript Objects for Beginners: Object Looping, Nested Objects & Methods Explained

    Labels

    Show more