Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate BMI JavaScript switch

I am doing a standard task with codewares: Write function bmi that calculates body mass index (bmi = weight / height2).

Here is my solution:

function bmi(weight, height) {
  let bmi = weight / (height ** 2)

  if (bmi <= 18.5) {

    return "Underweight";
  } else if (bmi <= 25.0) {

    return "Normal"
  } else if (bmi <= 30.0) {

    return "Overweight"
  } else if (bmi > 30) {
    return "Obese"
  }
}

console.log(bmi(80, 1.80))

I have a question: is it possible to solve this problem with the help of a switch? Because I tried it in different ways and in the console I have undefined:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function bmi(weight, height) {

  let bmi = weight / (height ** 2)

  let c = "Normal"

  switch (bmi) {
    case "Underweight":
      bmi <= 18.5;
      break;

    case "Normal":
      bmi <= 25.0;
      break;

    case "Overweight":
      bmi <= 30.0;
      break;

    default:
      return;
  }
}
console.log(bmi(80, 1.80))

>Solution :

You have switched your case and your outcome– that’s the issue. Here it is switched the right way:

function bmi(weight, height) {

  let bmi = weight / (height ** 2)

  let c = "Normal"

  switch (bmi) {
    case bmi <= 18.5:
      c = "Underweight";
      break;

    case bmi <= 25.0:
      c = "Normal";
      break;

    case bmi <= 30.0:
      c = "Overweight";
      break;

  }
  return c;
}

console.log(bmi(80, 1.80))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading