All JavaScript projects

JavaScript project

Product Inventory Manager

Track a small shop's products, stock quantities, and stock value, then update inventory when an item sells.

Step 3: Combine the earlier concepts with objects and property updates.

  • Variables
  • Data types
  • Operators
  • Conditions
  • Functions
  • Arrays
  • Loops
  • Objects

What you will build

  • Add products with a name, unit price, and opening stock quantity.
  • Keep each product's details together in one object and store the objects in an array.
  • Record one sale at a time, prevent sales when stock is zero, and remove a product when no longer needed.
  • Show total stock value at the entered unit prices. This is an in-memory practice tool; refreshing clears the inventory.

How to run this project

  1. Create a file named index.html in a new folder.
  2. Copy the complete code below into the file and save it.
  3. Open index.html in your browser. No installation or API key is needed.

Complete project code

This single file includes the HTML interface, basic CSS styling, and JavaScript behavior. The script runs after the HTML so all the elements are available.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Product Inventory Manager</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px; line-height: 1.6; }
    form { display: grid; gap: 12px; }
    input, select, button { font: inherit; padding: 8px; }
    button { cursor: pointer; }
    button:disabled { cursor: default; }
    li { margin: 12px 0; overflow-wrap: anywhere; }
    li button { margin-left: 12px; }
    input[type="checkbox"] { margin-right: 8px; }
    #answers { display: grid; gap: 8px; }
  </style>
</head>
<body>
<h1>Product Inventory Manager</h1>
<form id="product-form">
  <label for="product-name">Product name</label>
  <input id="product-name" maxlength="60" required>
  <label for="price">Unit price (Rs)</label>
  <input id="price" type="number" min="0.01" max="100000" step="0.01" required>
  <label for="quantity">Opening stock</label>
  <input id="quantity" type="number" min="0" max="10000" step="1" required>
  <button type="submit">Add product</button>
</form>
<p id="message" role="status"></p>
<h2>Products</h2>
<p id="empty-state">No products yet. Add your first product above.</p>
<ul id="product-list"></ul>
<p id="inventory-value" role="status"></p>
<script>
// 1. Each array entry will be a product object.
let products = [];
let nextId = 1;
const form = document.querySelector("#product-form");
const nameInput = document.querySelector("#product-name");
const priceInput = document.querySelector("#price");
const quantityInput = document.querySelector("#quantity");
const list = document.querySelector("#product-list");
const message = document.querySelector("#message");

function formatMoney(paise) {
  return "Rs " + (paise / 100).toFixed(2);
}

// 2. Find a product and update one of its properties.
function sellOne(productId) {
  const product = products.find((item) => item.id === productId);
  if (!product || product.quantity === 0) return;

  product.quantity -= 1;
  renderProducts();
  message.textContent = "Sold one " + product.name + ". Stock left: " + product.quantity;
  nameInput.focus();
}

function removeProduct(productId) {
  products = products.filter((item) => item.id !== productId);
  renderProducts();
  message.textContent = "Product removed.";
  nameInput.focus();
}

// 3. Read object properties to build the list and total.
function renderProducts() {
  list.replaceChildren();
  let totalValue = 0;

  for (const product of products) {
    const stockValue = product.pricePaise * product.quantity;
    totalValue += stockValue;

    const item = document.createElement("li");
    const title = document.createElement("strong");
    title.textContent = product.name;
    const details = document.createElement("p");
    details.textContent = "Price: " + formatMoney(product.pricePaise)
      + " | Stock: " + product.quantity
      + " | Value: " + formatMoney(stockValue);

    const sellButton = document.createElement("button");
    sellButton.type = "button";
    sellButton.textContent = product.quantity === 0 ? "Out of stock" : "Sell one";
    sellButton.disabled = product.quantity === 0;
    sellButton.setAttribute("aria-label", "Sell one " + product.name);
    sellButton.addEventListener("click", () => sellOne(product.id));

    const removeButton = document.createElement("button");
    removeButton.type = "button";
    removeButton.textContent = "Remove";
    removeButton.setAttribute("aria-label", "Remove " + product.name);
    removeButton.addEventListener("click", () => removeProduct(product.id));

    item.append(title, details, sellButton, removeButton);
    list.append(item);
  }

  document.querySelector("#empty-state").hidden = products.length > 0;
  document.querySelector("#inventory-value").textContent = "Total stock value: " + formatMoney(totalValue);
}

// 4. Validate input and create a new product object.
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const name = nameInput.value.trim();
  const price = priceInput.valueAsNumber;
  const quantity = quantityInput.valueAsNumber;

  if (name === "") {
    message.textContent = "Enter a product name.";
    return;
  }
  if (!Number.isFinite(price) || price < 0.01 || price > 100000) {
    message.textContent = "Enter a price from Rs 0.01 to Rs 100,000.";
    return;
  }
  if (!Number.isInteger(quantity) || quantity < 0 || quantity > 10000) {
    message.textContent = "Stock must be a whole number from 0 to 10,000.";
    return;
  }

  const existingProduct = products.find((product) => product.name.toLowerCase() === name.toLowerCase());
  if (existingProduct) {
    message.textContent = "A product with that name already exists.";
    return;
  }

  const product = {
    id: nextId,
    name: name,
    pricePaise: Math.round(price * 100),
    quantity: quantity
  };
  products.push(product);
  nextId += 1;
  renderProducts();
  form.reset();
  nameInput.focus();
  message.textContent = name + " added to inventory.";
});

renderProducts();
</script>
</body>
</html>

How the code works

  1. 1. Group related values in an object

    A product object stores its unique id, name, price in paise, and stock quantity together. name is a string; the other properties are numbers. Dot notation reads a property, such as product.quantity. This is more useful than separate arrays for names, prices, and quantities because each product's details stay together.

    JavaScript
    const product = {
      id: 1,
      name: "Notebook",
      pricePaise: 5000,
      quantity: 3
    };
    // product.name is "Notebook"; product.quantity is 3.
  2. 2. Validate and add products to an array

    The form checks the name, price, and quantity before creating an object. Number.isInteger prevents fractional stock such as 2.5 units. find checks for an existing product name; toLowerCase makes that check case-insensitive. push adds the new object, while nextId increments so removing one product never causes another to reuse its id.

  3. 3. Read objects inside a loop

    The for...of loop visits every product object. Multiplying pricePaise by quantity gives its stock value, and += accumulates the overall value. For example, three notebooks at Rs 50 contribute Rs 150. createElement and textContent display the data safely, including names that contain symbols.

  4. 4. Find an object and change its stock

    sellOne receives a product id. find returns the matching object, or undefined if it does not exist. The guard stops a missing or out-of-stock product from being sold. Updating product.quantity changes the same object held in the products array. const prevents reassigning the local product variable; it does not make the object's properties read-only.

    JavaScript
    const product = products.find((item) => item.id === productId);
    if (!product || product.quantity === 0) return;
    
    product.quantity -= 1;
  5. 5. Remove a product without changing other records

    filter creates an array containing every product except the matching id. products uses let because this operation assigns a new array to it. Both selling and removing call renderProducts again, so stock counts and total value stay synchronized with the data.

  6. 6. Combine the earlier topics in one workflow

    This project combines variables and data types, arithmetic and comparison operators, validation conditions, reusable functions, an array, a loop, and objects. Boolean expressions disable sales at zero stock, while the ternary operator chooses the button label. The small event callbacks pass the correct id to each function. This version tracks current stock, not revenue or sales history, and its data clears on refresh.

Try it yourself

Add Notebook at Rs 50 with stock 3 and Pen at Rs 10 with stock 5: total stock value is Rs 200. Sell one notebook: its stock becomes 2 and the total becomes Rs 150. Sell the other two notebooks: its button becomes Out of stock and the total is Rs 50. Try adding notebook again or stock 2.5; both should be rejected. Remove Pen and confirm the remaining stock value is Rs 0.

Back to all projects
Digital AI Academy

DevBrainBox Portal is proudly developed and managed by

Digital AI Academy
About the academy