Emmanuel Akinfulubi

JavaScriptBasic

BMI calculator in JavaScript

Beginner · 3 min read

Body mass index (BMI) is a quick number that compares a person's weight with their height. Health apps, fitness trackers and clinic forms show it, along with a label such as "normal" or "overweight". The math is one line. The interesting part is what happens when someone types their height in the wrong unit.

In this tutorial you will write bmi to do the calculation, band to pick the label, and bmiForgiving, which copes with a height typed in centimeters instead of meters. You need to know what a function is and what ** does (3 ** 2 is 3 squared, 9).

The formula

BMI is the weight in kilograms divided by the height in meters, squared:

Output

BMI = weight / (height × height)

For 70 kg and 1.75 m, the height squared is 1.75 times 1.75, which is 3.0625. Then 70 divided by 3.0625 is about 22.9.

The bands

The usual labels are:

  • under 18.5: underweight
  • 18.5 up to (but not including) 25: normal
  • 25 up to 30: overweight
  • 30 and above: obese

Notice the edges. Exactly 25 is "overweight", not "normal", because the normal band stops just before 25.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

67 Body mass index, and the unit trap

easy

Compute BMI from a weight in kilograms and a height in metres, and put the result in a band. Then see what happens when the height arrives in centimetres.

Stuck? Three hints, smallest first
  1. 1. BMI is weight divided by height squared, with height in metres.
  2. 2. A chain of ternaries reads well for bands, as long as each cut-off appears once.
  3. 3. A form that collects "height" will get 175 from some people and 1.75 from others. Decide what to do about it.

Step 1: the calculation

Step 1

const bmi = (kg, metres) => kg / metres ** 2;
console.log(bmi(70, 1.75));            // 22.857142857142858
console.log(bmi(70, 1.75).toFixed(1)); // 22.9

** is done before /, so metres ** 2 is worked out first, exactly as the formula needs. toFixed(1) rounds to one decimal place for display. It gives back text, so keep the unrounded number for any further math.

Step 2: pick a band with a ternary chain

The ternary operator condition ? a : b means "if the condition is true, a, otherwise b". You can chain them to test several cut-offs in a row:

Step 2

const band = (value) =>
  value < 18.5 ? 'underweight'
  : value < 25 ? 'normal'
  : value < 30 ? 'overweight'
  : 'obese';
console.log(band(22.9)); // normal
console.log(band(16.3)); // underweight
console.log(band(25));   // overweight
console.log(band(38));   // obese

Read it from the top. If the value is under 18.5, the answer is "underweight". If not, it must be at least 18.5, so value < 25 only has to check the top of the normal band. Each cut-off appears exactly once and they go up in order, which is what makes the chain correct. For 25, the < 25 test fails, so it moves on to "overweight".

Step 3: the unit trap

A form field says "Height". Some people type 1.75. Others type 175, meaning centimeters. Watch what happens:

JavaScript

const bmi = (kg, metres) => kg / metres ** 2;
console.log(bmi(70, 175).toFixed(5)); // 0.00229

No error is thrown. JavaScript happily divides 70 by 30,625 and gives a tiny number. Nothing in the calculation knows that 175 meters is not a human height. A wrong answer that looks like a normal number is the hardest kind of bug to notice.

Step 4: a forgiving version

No adult is taller than 3 meters, so a height above 3 must be in centimeters. Divide it by 100 before calculating:

Step 4

const bmi = (kg, metres) => kg / metres ** 2;
const bmiForgiving = (kg, height) => bmi(kg, height > 3 ? height / 100 : height);
console.log(bmiForgiving(70, 175).toFixed(1));        // 22.9
console.log(bmiForgiving(70, 1.75) === bmi(70, 1.75)); // true

A height in meters passes through untouched, so both ways of typing it give the same result. The other safe option is to make the unit part of the input, for example a separate "cm" or "m" choice, so the code never has to guess.

Step 5: put it together

Step 5

const bmi = (kg, metres) => kg / metres ** 2;
const band = (value) =>
  value < 18.5 ? 'underweight'
  : value < 25 ? 'normal'
  : value < 30 ? 'overweight'
  : 'obese';
console.log(bmi(50, 1.75).toFixed(1), band(bmi(50, 1.75)));   // 16.3 underweight
console.log(bmi(110, 1.7).toFixed(1), band(bmi(110, 1.7)));   // 38.1 obese

The band is chosen from the full-precision BMI, and only the displayed number is rounded.

The full solution

The answer panel has bmi, band and bmiForgiving, prints two people's BMI and band, the centimeter mistake, and the forgiving result. Its checks test both sides of the 25 boundary and the obese band. Press Run to see the output.

The answer

const bmi = (kg, metres) => kg / metres ** 2;

const band = (value) =>
  value < 18.5 ? 'underweight'
  : value < 25 ? 'normal'
  : value < 30 ? 'overweight'
  : 'obese';

// A height above 3 is centimetres, whatever the label on the field said.
const bmiForgiving = (kg, height) => bmi(kg, height > 3 ? height / 100 : height);

console.log('70kg at 1.75m ->', bmi(70, 1.75).toFixed(1), band(bmi(70, 1.75)));
console.log('50kg at 1.75m ->', bmi(50, 1.75).toFixed(1), band(bmi(50, 1.75)));
console.log('in centimetres by mistake ->', bmi(70, 175).toFixed(5));
console.log('forgiving version ->', bmiForgiving(70, 175).toFixed(1));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a normal BMI, rounded for display', Number(bmi(70, 1.75).toFixed(1)), 22.9);
test('and its band', band(bmi(70, 1.75)), 'normal');
test('a lower weight moves band', band(bmi(50, 1.75)), 'underweight');
test('exactly 25 is overweight, because the band is < 25', band(25), 'overweight');
test('centimetres give a nonsense answer rather than an error', Number(bmi(70, 175).toFixed(5)), 0.00229);
test('so the forgiving version normalises the unit', Number(bmiForgiving(70, 175).toFixed(1)), 22.9);
test('and leaves metres alone', bmiForgiving(70, 1.75) === bmi(70, 1.75), true);
test('the top band', band(bmi(110, 1.7)), 'obese');

The unit mix-up is the real subject. bmi(70, 175) does not throw, it returns 0.00229, and 0.00229 will render happily in a UI next to the word "normal" if the bands are checked in the wrong order. Range-check inputs whose unit is ambiguous, or take the unit as a separate argument.

The ternary chain works because each threshold appears exactly once and the order is ascending; that is also why band(25) is "overweight" — < 25 has already failed. Whenever a band boundary matters clinically or financially, assert both sides of it, as the fourth check does.

Common mistakes

  • Squaring the weight or forgetting to square the height. It is weight divided by height squared: kg / metres ** 2.
  • Putting the cut-offs out of order. If value < 30 came first, a BMI of 22 would be labeled "overweight".
  • Trusting the unit of a free-text field. 175 and 1.75 both arrive. Check the range or ask for the unit.

Try it yourself

  1. Find the BMI of 85 kg at 1.80 m, and its band.
  2. Make bmiForgiving throw an error when the height is 0 or less.
  3. Write bmiImperial(pounds, inches) using the formula 703 * pounds / inches ** 2, and compare it with the metric result for the same person.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.