# JavaScript program to calculate BMI with user input values

## JavaScript program to find BMI:

In this post, we will create a simple BMI calculator in JavaScript. I will show you how to write a simple JavaScript program and also how to use it with HTML & CSS files.

You will get an idea on how to write a JavaScript program with HTML/CSS files and how to take user inputs.

Before we start writing down the program, let me quickly explain to you what is BMI and the formula to calculate it.

### BMI:

If we divide the body weight in kilogram by the square of the height in meter, it will give us the BMI. So, if we get the body weight in kg and height in meter from the user, we can calculate the BMI by using the following formula:

``BMI = weight in kg/(height in meter)^2``

Let’s write down the program in JavaScript.

### JavaScript program to calculate BMI with user input values:

The below JavaScript program calculates the BMI with user input values:

``````let weight = 54;
let height = 2.6;

let bmi = Math.round(weight / (height * height));

console.log(`Weight: \${weight} kg, Height: \${height} m, BMI: \${bmi}`);``````

In this example, the weight and height values are given. The weight is in kg and the height is in meter. The BMI is calculated by using the above formula. We are also using Math.round function to round the value to its nearest integer. So, if the calculated value is 3.99, it will convert it to 4. The last line is printing the values of given weight, height and the calculated bmi.

It will print the below output:

``Weight: 54 kg, Height: 2.6 m, BMI: 8``

### Calculate BMI with HTML, CSS and JavaScript:

Let’s use HTML, CSS and JavaScript to calculate the BMI with user-input values. It will take the weight and height as inputs from the user and calculate the BMI.

``````<!DOCTYPE html>
<html lang="en">
<script>
function calculateBMI() {
let weight = document.getElementById("inputWeight").value;
let height = document.getElementById("inputHeight").value;

let bmi = Math.round(weight / (height * height));

document.getElementById("result").innerHTML = bmi;
}
</script>
<body>
<p>Enter the weight in KG:</p>
<input id="inputWeight" />
<p>Enter the height in Meter:</p>
<input id="inputHeight" />
<button onclick="calculateBMI()">Calculate BMI</button>
<p id="result"></p>
</body>
</html>``````

In this program,

• The HTML is written inside the body tags. The JavaScript part is written inside the script tags. It has one function called calculateBMI to calculate the BMI.
• We created two input fields to take the user inputs. One for the weight and another for the height.
• There is one button that calls the calculateBMI function on click. It reads the weight and height values from the input fields, calculates the BMI and shows this value in the result paragraph component.

You can create one index.html file with the above code and open it in any web browser to see the result.