Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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:

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

(Thanks to user derpirscher for pointing out I had provided a completely incorrect answer. I've updated a corrected answer below.)

Unfortunately this syntax for switch statements, where your case is a complex comparison against the expression, is not supported in JS. Cases are simply checked against the expression for a simple match. While one could do something like this:

function bmi(weight, height) {

  let bmi = weight / (height ** 2)

  let c = "Normal"

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

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

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

    default:
      c = "Obese"

  }
  return c;
}

console.log(bmi(8, 1.80))
console.log(bmi(80, 1.80))
console.log(bmi(800, 1.80))

It is using the switch for a case different than its intended purpose. This is not necessarily a readable or expressive way of writing this-- I think your original approach with the if...else is probably preferable to a switch-based approach.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!