skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 process

    2- 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

    function bmiCalculator(weight, height) {
      let result = "";
      let bmi = weight / Math.pow(height, 2)
      bmi = Math.round(bmi * 10) / 10;
    
      if (bmi <= 18.5) {
        result = "Your BMI is " + bmi + ", so you are underweight.";
      } else if (bmi > 18.5 && bmi <= 24.9) {
        result = "Your BMI is " + bmi + ", so you have a normal weight.";
      } else {
        result = "Your BMI is " + bmi + ", so you are overweight.";
      }
      return result;
    
    }
    
    console.log(bmiCalculator(55, 1.75))
    console.log(bmiCalculator(65, 1.75))
    console.log(bmiCalculator(92, 1.75))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search