I was trying a CodeWars easy challenge to calculate BMI and return a weight rating of Underweight - Obese. I was interested specifically on how I could implement this in a switch statement as I already submitted the If + If else variation. Additionally, when does switch statement become more viable in terms of clean code/performance.
Initially I submitted the if else variation.
function bmi(weight, height) {
let bmiCalc = (weight / (height*height));
if (bmiCalc <= 18.5){
return 'Underweight';
if else (bmiCalc <= 25.0){
return 'Normal';
if else (bmiCalc <= 30.0){
return 'Normal';
else (bmiCalc > 30.0){
return 'Obese';
}
}
I wondered then how a switch statement might look so I tried
function bmi(weight, height) {
let bmiCalc = (weight / (height * height));
switch (bmiCalc){
case (<= 18.5):
return 'Underweight';
case (<= 25.0):
return 'Normal';
case (<= 30.0):
return 'Overweight';
case (> 30.0):
return 'Obese';
}
}
Which ultimately spit out a unexpected token '<=' error. Is it possible to have such expressions in a switch statement.
I also tried to put in
case (bmiCalc <= 18.5){ return 'Underweight'}
Based on my findings from other languages, I saw that this expression would not work for my desired test case. Thanks in advance, hopefully not too silly of a question.