I know it’s basic but I’m trying to show the if statements depending on the input I put in the function but they do not show up. Only the result of the calculation of the variable shows up. If not I run the function it will only give me a number as a result. (It’s in kg and meters)
function bmiCalculator (weight, height) {
var bmi = weight / Math.pow(height,2)
return bmi = Math.round(bmi * 10) / 10;
if (bmi <= 18.5) {
("Your BMI is " + bmi + ", so you are underweight.");
}
if (bmi > 18.5 && bmi === 24.9) {
("Your BMI is " + bmi + ", so you have a normal weight.");
}
if (bmi > 24.9) {
("Your BMI is " + bmi + ", so you are overweight.");
}
}
I was expecting to get the if statements depending on your BMI. I tried changing the if statements to different places to see if it worked but nothing.
2
Answers
Observe the code. You put the return statement before the if statements,
so your program will never reach them, and will return only what it says it will return, e.g. the BMI.
Furthermore, it seems that you want to return the String corresponding the conditions, so you should write if… return "Your BMI is…" etc.
When you return the result of a function, the process ends there which means it won’t read the rest of the code(any of the if statements written there won’t be read).
This is what you should do instead:
1- use
let
to declare variables that will change during the process2- declare a single variable that will be your result that you will return form your function and after your conditions you can return it just once.
3- fix your conditions a bit, this line here is not doing what you expect it to do:
if (bmi > 18.5 && bmi === 24.9) {
4- finally return your result just once at the end of the function