Build a Spice Freshness Tracker in Vanilla JavaScript
Small projects are the best way to practise JavaScript, especially when they solve a real kitchen problem. In this tutorial we will build a spice freshness tracker: you add each jar with the date you opened it, and the a
Small projects are the best way to practise JavaScript, especially when they solve a real kitchen problem. In this tutorial we will build a spice freshness tracker: you add each jar with the date you opened it, and the app tells you which ones are fresh, which to use soon and which to replace.
Why spices? Ground spices fade slowly, and people rarely notice the day a jar stops smelling like itself. Guides on the best Indian spices keep repeating the same habit: write the opening date on every jar and replace what has faded. A tiny app can do that bookkeeping for you.
No framework, no build step. Just HTML and plain JavaScript.
What We Are Building
A page where the user:
Enters a spice name and the date the jar was opened.
Picks how many months they want it to last.
Sees a list with a status for each jar: fresh, use soon or replace.
One note on the numbers. Real shelf life depends on the spice, the packaging and how it is stored, so the months are a setting the user chooses, not a rule from the app. Many kitchen guides suggest finishing ground spices within a few months of opening, and we will default to 6 months as a starting point only.
Step 1: The HTML
html
<!DOCTYPE html>
Spice Freshness Tracker
<form id="spice-form">
<label>Spice name
<input type="text" name="name" required />
</label>
<label>Opened on
<input type="date" name="openedOn" required />
</label>
<label>Plan to finish within (months)
<input type="number" name="shelfLifeMonths" min="1" max="36" value="6" required />
</label>
<button type="submit">Add jar</button>
</form>
<ul id="jar-list"></ul>
Step 2: The Core Logic
Create app.js. We keep the date logic in pure functions so they are easy to test.
js
function addMonths(date, months) {
const d = new Date(date.getFullYear(), date.getMonth() + months, 1);
const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
d.setDate(Math.min(date.getDate(), lastDay));
return d;
}
function getStatus(item, today = new Date()) {
const opened = new Date(item.openedOn + "T00:00:00");
if (Number.isNaN(opened.getTime())) {
return { status: "invalid", message: "Check the opened date." };
}
const replaceBy = addMonths(opened, item.shelfLifeMonths);
const msPerDay = 24 * 60 * 60 * 1000;
const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate());
const daysLeft = Math.round((replaceBy - startOfToday) / msPerDay);
if (daysLeft < 0) return { status: "replace", daysLeft };
if (daysLeft <= 30) return { status: "use-soon", daysLeft };
return { status: "fresh", daysLeft };
}
Two details worth noticing:
addMonths clamps the day. Adding one month to 31 January with plain setMonth would overflow into March. We build the target month first and use the smaller of the original day and that monthβs last day.
today is a parameter. That lets us test with a fixed date instead of the real clock.
Step 3: Render the List
js
const jars = []; // in-memory for this demo
const form = document.getElementById("spice-form");
const list = document.getElementById("jar-list");
const labels = {
fresh: "Fresh",
"use-soon": "Use soon",
replace: "Replace",
invalid: "Invalid date",
};
function render() {
list.innerHTML = "";
jars.forEach((jar) => {
const result = getStatus(jar);
const li = document.createElement("li");
const detail =
result.daysLeft === undefined
? result.message
: result.daysLeft < 0
? `${Math.abs(result.daysLeft)} days past plan`
: `${result.daysLeft} days left`;
li.textContent = `${jar.name}: ${labels[result.status]} (${detail})`;
list.appendChild(li);
});
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(form));
jars.push({
name: data.name.trim(),
openedOn: data.openedOn,
shelfLifeMonths: Number(data.shelfLifeMonths),
});
form.reset();
render();
});
We use textContent instead of innerHTML, so a jar named cumin shows as plain text and cannot inject markup.
Step 4: Test It
js
const today = new Date(2026, 10, 25); // 25 Nov 2026
console.log(addMonths(new Date(2026, 0, 31), 1).toDateString());
// "Sat Feb 28 2026"
console.log(getStatus({ openedOn: "2026-10-01", shelfLifeMonths: 6 }, today));
// { status: "fresh", daysLeft: 127 }
console.log(getStatus({ openedOn: "2026-06-10", shelfLifeMonths: 6 }, today));
// { status: "use-soon", daysLeft: 15 }
console.log(getStatus({ openedOn: "2026-01-05", shelfLifeMonths: 6 }, today));
// { status: "replace", daysLeft: -143 }
Paste these into the browser console after app.js loads, or run the two functions in Node. The expected values above come from running this exact code.
Step 5: Make It Better
Persist the list. Save jars with localStorage and load it on page start. Wrap JSON.parse in try/catch, because stored data can be missing or broken.
Add a delete button so replaced jars can be removed.
Sort by urgency, with replace first and fresh last.
Different defaults per spice. Whole spices usually stay aromatic longer than ground ones, so you could store a default per type.
Group by category. Single spices and blends could sit in separate lists.
Common Mistakes
Using setMonth directly and getting a wrong date when the day does not exist in the target month.
Parsing "2026-10-01" without a time part and getting time-zone surprises. Adding T00:00:00 keeps it as a local date.
Comparing dates that still contain a time of day, instead of rounding to the start of the day.
Using innerHTML with user input.
Treating the trackerβs output as a food-safety verdict. It is only a reminder based on the number you chose.
A Note on Real Kitchens
The app is only as useful as the habits around it. The jar still needs a quick smell test, and a weak aroma beats any date. If you want a starter list of what a small, fresh masala box can contain, this guide to the best Indian spices for everyday cooking is a good reference. The same idea works for anyone who plans to buy Indian spices, whether in a shop or from Indian spices online sellers: track what you open, and reorder only what runs out.
A tracker also helps with ordering. When you order Indian spices, your list of βreplaceβ items becomes the shopping list. That means smaller, more frequent orders instead of one large stock-up that goes stale. And when you check labels for authentic Indian spices, you can feed the packed-on date straight into the tracker.
If you want ideas on what to do with fresh jars, this piece on how the best Indian spices turn simple homemade meals into delicious dishes covers tadka, rice and simple vegetable dishes. It also helps to remember that Indian spice blends often have their own freshness window, so give blends their own entry and shelf-life setting.
FAQ
Is six months the right shelf life?
It is only a default. Real freshness depends on the spice, packaging and storage, so let the user change it, and always trust the smell test too.
Why not use Date arithmetic with days instead of months?
Months are how people think about βfinish within a few monthsβ, and addMonths handles different month lengths for you.
Why does getStatus accept today?
It makes the function predictable and testable, because the result no longer depends on the real clock.
Can I use this for other pantry items?
Yes. Rename the labels and change the default shelf life, and it works for tea, flour, lentils and more.
Do I need a framework?
Not for this size. Plain JavaScript is enough, and the pure functions can be reused in React or Vue later.
Wrapping Up
In about 80 lines we built a small tracker with date arithmetic, a testable status function and safe DOM rendering. It is a good beginner project because it covers forms, FormData, dates, arrays and edge cases like month-end dates.
If you build it, tell me which feature you would add first.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.