A nutrition calculator looks simple: add up some numbers. In practice you hit a few real problems. Food data is stored per 100 g but people eat 50 g or 200 g. Label calories don't quite match the macros. Net carbs depend on fibre. And a daily goal has to turn percentages into grams.
This post builds the core of one in plain JavaScript, with no libraries. I ran every example in Node before writing it down. The finished tool is here: free nutrition calculator.
Step 1: Scale per-100 g data to any amount
Most food tables give values per 100 g. To get any portion, multiply by grams / 100:
const KCAL = { protein: 4, carbs: 4, fat: 9 }; function scale(food, grams) { if (!Number.isFinite(grams) || grams <= 0) throw new Error("Enter an amount above 0"); const k = grams / 100; const out = {}; for (const key of ["kcal", "protein", "carbs", "fat", "fiber"]) out[key] = (food[key] || 0) * k; return out; } Number.isFinite rejects NaN and Infinity, which is what you get from an empty input box. (food[key] || 0) handles foods with no fibre value.
The values below are rounded examples to show the maths, not a food database:
const oats = { kcal: 389, protein: 16.9, carbs: 66.3, fat: 6.9, fiber: 10.6 }; const milk = { kcal: 42, protein: 3.4, carbs: 5, fat: 1 }; scale(oats, 50); // kcal 194.5, protein 8.45, carbs 33.15, fat 3.45, fiber 5.3 scale(milk, 200); // kcal 84, protein 6.8, carbs 10, fat 2, fiber 0 Step 2: Add up a meal and work out net carbs
function totals(entries) { const t = { kcal: 0, protein: 0, carbs: 0, fat: 0, fiber: 0 }; for (const e of entries) for (const key in t) t[key] += e[key]; t.netCarbs = Math.max(0, t.carbs - t.fiber); return t; } Net carbs are total carbohydrates minus fibre. Math.max(0, ...) stops bad data from producing a negative number. For 50 g of oats plus 200 g of milk:
kcal 278.5 | protein 15.3 g | carbs 43.2 g | fat 5.5 g | fibre 5.3 g | net carbs 37.9 g Step 3: The macro split, and why label calories don't add up
Protein and carbohydrate provide about 4 calories per gram, and fat about 9. You can show what share of calories comes from each:
function macroSplit(t) { const p = t.protein * KCAL.protein, c = t.carbs * KCAL.carbs, f = t.fat * KCAL.fat; const sum = p + c + f; if (sum === 0) return { protein: 0, carbs: 0, fat: 0 }; return { protein: (p / sum) * 100, carbs: (c / sum) * 100, fat: (f / sum) * 100 }; } For the meal above this gives about 22% protein, 61% carbs and 17% fat.
Notice that I divide by the macro calories, not by the label calories. In my oats example the label says 389 kcal, but 4 × 16.9 + 4 × 66.3 + 9 × 6.9 is about 395. Labels round values, and fibre and other factors shift the totals. If you divide by the label calories, your three percentages won't add up to 100. If you divide by the macro calories, they always do. The sum === 0 check also stops a division by zero on an empty log.
Step 4: Turn a calorie goal into grams
Presets are usually percentages, such as 25% protein, 50% carbs and 25% fat. To make them useful, convert them to grams:
function macroGoals(calories, split) { const total = split.protein + split.carbs + split.fat; if (Math.abs(total - 100) > 0.01) throw new Error("Split must add up to 100"); return { protein: (calories * split.protein / 100) / KCAL.protein, carbs: (calories * split.carbs / 100) / KCAL.carbs, fat: (calories * split.fat / 100) / KCAL.fat, }; } macroGoals(2000, { protein: 25, carbs: 50, fat: 25 }); // protein 125 g, carbs 250 g, fat 55.6 g The check on the total stops a typo like 30/50/30 from silently giving a wrong plan. Fat comes out at 55.6 g because it has 9 calories per gram, not 4.
Step 5: Save the log without crashing
A food log is annoying to lose, so keep it in localStorage. Storage can be missing or blocked, so wrap every access:
function save(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch (e) {} } function load(key, fallback) { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch (e) { return fallback; } } The page then works even in a private window, and nothing is sent to a server. I tested this in Node, where localStorage doesn't exist, and load returned the fallback instead of throwing.
What I tested
- Scaling 50 g of oats gives 194.5 kcal and 8.45 g protein.
- Totals, net carbs and the three macro percentages (which add up to 100).
- An empty log returns 0% for everything, with no errors.
- A goal split that doesn't add up to 100 throws.
- Zero or
NaNamounts throw. - Net carbs never go below 0.
- Missing
localStoragedoesn't crash.
Limits worth being honest about
This is a calculator, not a diet plan. Food tables are averages, labels are rounded, and the 4/4/9 figures are approximations. Needs vary by person, so any goal should be a starting point you adjust, and anyone with a health condition should check with a doctor or dietitian. If you build one for others, say so on the page.
Where to take it next
- A search box over your food list, with grams or servings.
- Custom foods that people can add themselves.
- A calorie target worked out from age, weight and activity. I covered that part in a guide to daily calorie needs.
- Fibre goals and a progress bar.
If you want to see these functions inside a finished interface, with a food list, meal totals, goal presets and a macro split chart, the nutrition calculator has them. I build the tools on ToolPond as a solo developer, and I'd welcome bug reports from anyone who finds a wrong total.