Home > Web Front-end > JS Tutorial > body text

Step-by-Step Guide to Building a Beginner-Friendly Shopping Cart in JavaScript Using Arrays and Functions

Susan Sarandon
Release: 2024-10-06 08:16:02
Original
465 people have browsed it

Step-by-Step Guide to Building a Beginner-Friendly Shopping Cart in JavaScript Using Arrays and Functions

The best way to learn a new programming language is by creating as many projects as possible. You will have a smoother experience as a beginner if you build mini-projects that focus on what you have learned.
The goal is to avoid "tutorial hell"—that scary place where you keep watching several tutorial videos without having any concrete project to show your skills—and also build the confidence necessary to tackle larger-scale projects.
In this article, I will explain how you can create a shopping cart system as a beginner, using basic Javascript concepts.

Prerequisites

To attempt this project, you would need to have in-depth knowledge of:

  • Functions
  • Methods
  • Arrays

What to Build?

The shopping cart will have a system where users can:

  • Add items to cart
  • Remove items from the cart
  • View the cart contents
  • Calculate the total price of items in the cart

Step 1: Setting Up the Data

To begin, we need to create a few arrays that will hold the data for our items. The arrays needed specifically are:

  • itemNames: Specifies the name of each item.
  • itemPrices: Contains the price each item costs.
  • itemQuantities: Tells how much of a specific item is available.
  • itemInStock: Determines if an item is in stock through the use of true or false.

const itemNames = ["Laptop", "Phone"];
const itemPrices = [1000, 500];
const itemQuantities = [1, 2];
const itemInStock = [true, true];


Copy after login

Step 2: Building the Shopping Cart with Functions

We are going to create a main shopping cart function that will contain the logic for the cart. We will use closures to ensure the cart stays private and only certain functions can interact with it.


const ShoppingCart = () => {
  const cart = []; // The cart is a private array

  // Add an item to the cart
  const addItemToCart = (itemIndex) => {
    if (itemInStock[itemIndex]) {
      cart.push(itemIndex);
      console.log(`${itemNames[itemIndex]} added to the cart`);
    } else {
      console.log(`${itemNames[itemIndex]} is out of stock`);
    }
  };

  // Remove an item from the cart
  const removeItemFromCart = (itemIndex) => {
    const index = cart.indexOf(itemIndex);
    if (index > -1) {
      cart.splice(index, 1);
    }
  };

  // Get the names of items in the cart
  const getCartItems = () => {
    return cart.map(itemIndex => itemNames[itemIndex]);
  };

  // Calculate the total price of items in the cart
  const calculateTotal = () => {
    return cart.reduce((total, itemIndex) => {
      return total + itemPrices[itemIndex] * itemQuantities[itemIndex];
    }, 0);
  };

  return {
    addItemToCart,
    removeItemFromCart,
    getCartItems,
    calculateTotal
  };
};


Copy after login

To break down the code:

  • addItemToCart(itemIndex): Adds an item to the cart based on its index (only if it is in stock).
  • removeItemFromCart(itemIndex): Removes an item from the cart using its index.
  • getCartItems(): Returns the name of the items in the cart using map() to convert the indices to names.
  • calculateTotal(): Calculates the total price by multiplying the prices and quantities of items in the cart using the reduce() method.

Step 3: Testing the Shopping Cart

A finished project should be tested to ensure it works as needed. We are going to test for:

  • adding items

  • viewing the cart

  • checking total price


const myCart = ShoppingCart();

// Add a Laptop (item 0)
myCart.addItemToCart(0);

// Add a Phone (item 1)
myCart.addItemToCart(1);

// View cart contents
console.log(myCart.getCartItems()); // Output: ['Laptop', 'Phone']

// Calculate the total price
console.log(myCart.calculateTotal()); // Output: 2000


Copy after login

To break down the code:

  • We create an instance of the shopping cart by calling it: const myCart = shoppingCart();.
  • We add items to the cart using their index from the itemNames array: myCart.addItemToCart(0); for the Laptop and myCart.addItemTocart(1); for the Phone.
  • We use getCartItems() to print the names of the items in the cart
  • Finally, we calculate the total price using calculateTotal().

Step 4: Removing Items from the Cart

A good shopping cart system must allow the user to remove items from the cart. We can do this by calling removeItemFromCart().


myCart.removeItemFromCart(1); // Remove the Phone

// View the updated cart
console.log(myCart.getCartItems()); // Output: ['Laptop']

// Recalculate the total price
console.log(myCart.calculateTotal()); // Output: 1000



Copy after login

Bonus: Understanding Closures in the Shopping Cart System

Closures help the cart array remain private, only accessible through the functions returned by the ShoppingCart() function.

  • The cart array is defined inside the shopping cart() and cannot be accessed directly from outside. However, because the addItemTocart(), removeItemFromCart(), getCartItems() and calculateTotal() functions are defined inside the same scope, they can interact with cart.
  • Closures are a powerful feature of JavaScript that help maintain data privacy and structure in your code.

Conclusion

By using basic arrays and functions, you've built a fully functional shopping cart system that can add, remove, and calculate totals for items. The awesome part of this project is that it uses closures to encapsulate and manage state without requiring complex objects or classes.

Final Code


const itemNames = ["Laptop", "Phone"];
const itemPrices = [1000, 500];
const itemQuantities = [1, 2];
const itemInStock = [true, true];

const ShoppingCart = () => {
  const cart = [];

  const addItemToCart = (itemIndex) => {
    if (itemInStock[itemIndex]) {
      cart.push(itemIndex);
      console.log(`${itemNames[itemIndex]} added to the cart`);
    } else {
      console.log(`${itemNames[itemIndex]} is out of stock`);
    }
  };

  const removeItemFromCart = (itemIndex) => {
    const index = cart.indexOf(itemIndex);
    if (index > -1) {
      cart.splice(index, 1);
    }
  };

  const getCartItems = () => {
    return cart.map(itemIndex => itemNames[itemIndex]);
  };

  const calculateTotal = () => {
    return cart.reduce((total, itemIndex) => {
      return total + itemPrices[itemIndex] * itemQuantities[itemIndex];
    }, 0);
  };

  return {
    addItemToCart,
    removeItemFromCart,
    getCartItems,
    calculateTotal
  };
};

const myCart = ShoppingCart();
myCart.addItemToCart(0);
myCart.addItemToCart(1);
console.log(myCart.getCartItems());
console.log(myCart.calculateTotal());
myCart.removeItemFromCart(1);
console.log(myCart.getCartItems());
console.log(myCart.calculateTotal());


Copy after login

I hope you enjoyed learning, and I am excited for you to build more awesome projects!

The above is the detailed content of Step-by-Step Guide to Building a Beginner-Friendly Shopping Cart in JavaScript Using Arrays and Functions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!