Menu

Build a Nutrition Calculator in Plain JavaScript
📰

Build a Nutrition Calculator in Plain JavaScript

DEV Community: javascript·shahid abbas·about 6 hours ago
#Wv4AaLXj
#devtojavascript#devto#dev#carbs#food
Long article (1304 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.