How to build a simple online calculator in JavaScript

js

Online calculators are among the simplest yet most frequently used interactive elements on the web. Whether it’s a financial calculator, a physics formula, or even a basic health indicator, the logic is always the same: user input + formula + result output.

In this tutorial, we’ll show how a working web calculator can be created with just a few lines of JavaScript. As an example, we’ll use the Body Mass Index (BMI) formula. It’s short, easy to understand, and illustrates how a mathematical formula can be implemented directly in the browser.

The BMI formula

The BMI is defined as:

BMI = weight (kg) / height (m)2

Example: a 70 kg person with a height of 1.75 m:

BMI = 70 / 1.752 ≈ 22.86

Basic HTML structure

<div>
  <label>Weight (kg):</label>
  <input type="number" id="weight" placeholder="e.g. 70">

  <label>Height (cm):</label>
  <input type="number" id="height" placeholder="e.g. 175">

  <button onclick="calculateBMI()">Calculate</button>

  <p id="result"></p>
</div>

JavaScript logic

<script>
function calculateBMI() {
  const weight = parseFloat(document.getElementById("weight").value);
  const height = parseFloat(document.getElementById("height").value) / 100; // cm → m
  if (!weight || !height) {
    document.getElementById("result").innerText = "Please enter valid values!";
    return;
  }
  const bmi = weight / (height * height);
  document.getElementById("result").innerText = "Your BMI is: " + bmi.toFixed(2);
}
</script>

You can try the full, responsive and mobile-friendly BMI calculator here: BMI Calculator →

Developer tips

  • Validation: always check that users don’t enter zero or negative values.
  • UI/UX: using type="number" helps on mobile, since it opens a numeric keypad.
  • Responsive layout: a simple CSS grid or flexbox keeps it clean across devices.
  • Extensions: you can add categories (underweight, normal, overweight, obese) based on the calculated BMI.

👉 With this short tutorial, your readers get both a working calculator and a clear example of how easy it is to turn a formula into an interactive web tool.



Image(s) used in this article are either AI-generated or sourced from royalty-free platforms like Pixabay or Pexels.

Did you enjoy this article? Buy me a coffee!

Buy Me A Coffee
Top