Skip to content
-
Design a BMI Calculator using JavaScript
Last Updated :
18 Apr, 2025
A BMI (Body Mass Index) Calculator measures body fat based on weight and height, providing a numerical value to categorize individuals as underweight, normal weight, overweight, or obese. It’s widely used to assess health risks and guide lifestyle or medical decisions.
A BMI Calculator using JavaScript allows users to input their weight and height, then calculates and displays their Body Mass Index (BMI), helping assess whether they are underweight, normal weight, or overweight.
BMI = (weight) / (height * height)
// height in cms and weight in kgs
Example:
- Weight: 70 kg
- Height: 170 cm
Height in meters = 170 cm / 100 = 1.7 m
BMI = 70 / (1.7 * 1.7)
BMI = 70 / 2.89
BMI ≈ 24.22
Output Preview:
Image PreviewApproach
BMI is a number calculated from an individual's weight and height.
- Collect height and weight from the user, stored in `height` and `weight` variables.
- Compute BMI by dividing weight (kg) by the square of height (m²).
- Use if-else statements to interpret the BMI result and determine the category.
- Check for empty inputs; if any are missing, display messages to provide height or weight.
- Use HTML for structure, CSS for styling, and JavaScript for input processing and output display.
In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed.
Example: In this example, we will structure in the index.html file and implement the logic in the app.js file
HTML
<!-- index.html file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BMI Calculator</title>
</head>
<body style="background-color: rgb(244, 255, 244)">
<div class="container">
<h1>BMI Calculator</h1>
<!-- Option for providing height
and weight to the user-->
<p>Height (in cm)</p>
<input type="text" id="height" />
<p>Weight (in kg)</p>
<input type="text" id="weight" />
<button id="btn">Calculate</button>
<div id="result"></div>
</div>
</body>
</html>
JavaScript
window.onload = () => {
let button = document.querySelector("#btn");
// Function for calculating BMI
button.addEventListener("click", calculateBMI);
};
function calculateBMI() {
/* Getting input from user into height variable.
Input is string so typecasting is necessary. */
let height = parseInt(document
.querySelector("#height").value);
/* Getting input from user into weight variable.
Input is string so typecasting is necessary.*/
let weight = parseInt(document
.querySelector("#weight").value);
let result = document.querySelector("#result");
// Checking the user providing a proper
// value or not
if (height === "" || isNaN(height))
result.innerHTML = "Provide a valid Height!";
else if (weight === "" || isNaN(weight))
result.innerHTML = "Provide a valid Weight!";
// If both input is valid, calculate the bmi
else {
// Fixing upto 2 decimal places
let bmi = (weight / ((height * height)
/ 10000)).toFixed(2);
// Dividing as per the bmi conditions
if (bmi < 18.6) result.innerHTML =
`Under Weight : <span>${bmi}</span>`;
else if (bmi >= 18.6 && bmi < 24.9)
result.innerHTML =
`Normal : <span>${bmi}</span>`;
else result.innerHTML =
`Over Weight : <span>${bmi}</span>`;
}
}
Output:

Similar Reads
HTML Calculator HTML calculator is used for performing basic mathematical operations like Addition, subtraction, multiplication, and division.You can find the live preview below, try it: To design the basic calculator, we will use HTML , CSS , and JavaScript . HTML is used to design the basic structure of the calcu
3 min read
JavaScript Calculator To build a simple calculator using JavaScript, we need to handle basic arithmetic operations such as addition, subtraction, multiplication, and division. JavaScript, along with HTML and CSS, is commonly used to create interactive web-based calculators.What We Are Going to CreateWe will build a simpl
7 min read
JavaScript Scientific Calculator The HTML Scientific Calculator is a tool for performing advanced scientific calculations like finding exponents, logarithms, factorials, and more. This calculator comprises two sections: the input section, where the user types in their mathematical problem, and the output screen, which displays all
4 min read
JavaScript Neumorphism Effect Calculator In this article, we will learn how to create a working calculator with the Neumorphism effect using HTML, CSS, and JavaScript. Basic mathematical operations such as addition, subtraction, multiplication, and division can be performed using this calculator. Approach: Neumorphism is a contemporary app
3 min read
JavaScript Age Calculator In the Age Calculator, the user enters their date of birth using a date input field. The tool calculates and displays the exact age in years, months, and days from the current date (or a specified date). We'll design the layout using HTML and CSS, and add functionality using JavaScript. It will also
3 min read
JavaScript Tip Calculator The tip is the money given as a gift for good service to the person who serves you in a restaurant. In this project, a simple tip calculator is made that takes the billing amount, type of service, and the number of persons as input. As per the three inputs, it generates a tip for the serving person.
4 min read
JavaScript Geometry Calculator In this article, we will see how to design a Geometry Calculator using HTML, CSS, and JavaScript. A Geometry calculator is used to calculate the area and parameters of different shapes and figures, like circles, rectangles, squares, triangles, etc. This can be helpful in cases where one wants to cal
4 min read
JavaScript Aspect Ratio Calculator In this article, we are going to implement an aspect ratio calculator. An aspect ratio calculator proves to be a useful tool for individuals seeking to determine the proportions of images or videos based on their width and height. Our aspect ratio calculator has a live preview option that enables us
5 min read
JavaScript Binary Calculator HTML or HyperText Markup Language along with CSS (Cascading Stylesheet) and JavaScript can be used to develop interactive user applications that can perform certain functionalities. Similarly, a binary calculator can be developed using HTML, CSS, and JS altogether. Binary Calculator performs arithme
5 min read
JavaScript Percentage Calculator The percentage calculator is useful for students, shopkeepers, and for solving basic mathematical problems related to percentages. In this article, we are going to learn, how to make a percentage calculator using HTML CSS, and JavaScriptFormula used:What is X percent of Y is given by the formula: X
3 min read
JavaScript Profit and Loss Calculator In this article, we will create a profit & loss calculator using HTML, CSS & Javascript for adding the basic functionality along with adding the design and layout. Profit and Loss Calculator is basically used to calculate the amount or percentage received after selling a particular price or
3 min read
JavaScript BMI Calculator A BMI (Body Mass Index) Calculator measures body fat based on weight and height, providing a numerical value to categorize individuals as underweight, normal weight, overweight, or obese. Itâs widely used to assess health risks and guide lifestyle or medical decisions.A BMI Calculator using JavaScri
3 min read
JavaScript Temperature Calculator In this article, we will see Temperature Conversion between Celsius, Fahrenheit & Kelvin using HTML CSS & JavaScript. The Temperature is generally measured in terms of unit degree., i.e. in degrees centigrade, in degrees, Fahrenheit & Kelvin. Celsius is a standard unit of temperature on
3 min read
JavaScript Student Grade Calculator A Student Grade Calculator is a tool used to compute students' grades based on their scores in various assessments, such as assignments, quizzes, exams, or projects. It helps standardize grading, ensures accuracy, and provides students with a clear understanding of their academic performance.Formula
4 min read
JavaScript Loan Calculator The Loan Calculator can be used to calculate the monthly EMI of the loan by taking the total amount, months to repay, and the rate of interest.Formula Used:interest = (amount * (rate * 0.01))/months;total = ((amount/months) + interest);ApproachExtract values from HTML input elements (#amount, #rate,
2 min read
JavaScript Interest Calculator Simple Interest is the term used to describe the rate at which money is borrowed or lent. Simple Interest Calculator serves as a practical tool for computing interest on loans or savings without compounding. It allows you to determine the simple interest on the principal amount, offering flexibility
3 min read
JavaScript CGPA Calculator Nowadays, colleges use grades like A, B, C, D, and F, and assign credits to courses. In this calculator, you just need to input your subject name, grade, and credit. We'll also include options to update or delete information in case of mistakes. This way, you won't have to re-enter all details if yo
4 min read
JavaScript Bartletts Test Calculator In this article, we are going to implement Bartlett's test calculator in JavaScript. Bartlett's test is a statistical test used to determine whether the variances of multiple groups are homogeneous and plays a crucial role in various fields of experimental research such as analysis of variance and h
3 min read
JavaScript Unit Converter In this article, we will be developing an interactive and styled unit converter using HTML, CSS, and JavaScript.In this application, we have a select category option box in which different types of units are specified, like temperature, area, weight, length, and time. As per the user selection, the
7 min read
JavaScript Length Converter In this article, we will learn how to create a length converter using HTML, CSS, and JavaScript. The Length Converter is an intuitive web-based application that eliminates the complexities associated with manual conversions. Its user-friendly interface allows users to input a numerical value and sel
6 min read
top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}