DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a BMI Calculator App with JavaScript

A BMI calculator is a classic beginner project because it is useful, it is short, and it teaches you how to turn a real-world formula into a working app. In this tutorial we will build one with plain HTML, CSS, and JavaScript.

BMI, or Body Mass Index, is weight in kilograms divided by height in metres squared. The app takes the user's height and weight, calculates the BMI, and shows which category it falls into: underweight, healthy, overweight, or obese.

<input id="height" type="number" placeholder="Height (cm)">
<input id="weight" type="number" placeholder="Weight (kg)">
<button onclick="calculateBMI()">Calculate BMI</button>
<p id="result"></p>
<p id="category"></p>
Enter fullscreen mode Exit fullscreen mode
function calculateBMI() {
  const heightCm = Number(document.getElementById('height').value);
  const weight = Number(document.getElementById('weight').value);
  const heightM = heightCm / 100;

  if (!heightM || !weight) {
    document.getElementById('result').textContent = 'Please enter height and weight.';
    return;
  }

  const bmi = weight / (heightM * heightM);
  let category = '';
  if (bmi < 18.5) category = 'Underweight';
  else if (bmi < 25) category = 'Healthy weight';
  else if (bmi < 30) category = 'Overweight';
  else category = 'Obese';

  document.getElementById('result').textContent = `Your BMI is ${bmi.toFixed(1)}`;
  document.getElementById('category').textContent = `Category: ${category}`;
}
Enter fullscreen mode Exit fullscreen mode

Why build this? It teaches input validation — the if (!heightM || !weight) check stops the app breaking on empty fields — and it teaches if/else chains with real thresholds instead of made-up examples. The category logic is the kind of branching you will write in almost every app.

A few ideas to extend it: show the healthy weight range for the user's height, add a history list that saves past results in localStorage, or colour the result green, yellow, or red by category. Each one is a small feature and a good next lesson.

One honest note to include in the app: BMI is a rough screening number, not a diagnosis. It does not account for muscle mass or body type, so treat the result as a starting point, not a verdict.

Top comments (0)