Home > Article > Web Front-end > 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.
To attempt this project, you would need to have in-depth knowledge of:
The shopping cart will have a system where users can:
To begin, we need to create a few arrays that will hold the data for our items. The arrays needed specifically are:
const itemNames = ["Laptop", "Phone"]; const itemPrices = [1000, 500]; const itemQuantities = [1, 2]; const itemInStock = [true, true];
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 }; };
To break down the code:
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
To break down the code:
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
Closures help the cart array remain private, only accessible through the functions returned by the ShoppingCart() function.
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.
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());
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!