I'm trying to make a BMI calculator.
If you give a weight that is a string, negative number, or so forth it should write back (type in validate weight etc.) in console. But the thing is, I don't know how to return just the conditions for typing in weight and height, so if I type in wrong values for both it doesn't write back in console your BMI etc. But also, if I type, for example, good values for weight and height it actually returns BMI.
Here's the code
let weight = 70
let height = 1.85
if (typeof weight !== 'number' || weight < 0) {
console.log("Type in validate weight ")
}
if (typeof height !== 'number' || height < 0) {
console.log("Type in validate height ")
}
function square(height) {
return (height * height);
}
var result = BMI(height,
weight);
function BMI(height, weight) {
return (weight /
square(height))
}
console.log(result);
if (result < 18.5) {
console.log("Your BMI is too low ")
} else if (result < 25) {
console.log("Your BMI is correct ")
} else if (result < 30) {
console.log("Your BMI is a little too high ")
} else if (result >= 30) {
console.log("Your BMI is too high ")
}
Do your validation all in one step, a function is a good way to achieve that, cand call it from your calculation
function validateInputs(weight,height){
let isValid = true;
if (typeof weight !== 'number' || weight < 0) {
console.log("Type in validate weight ")
isValid = false;
}
if (typeof height !== 'number' || height < 0) {
console.log("Type in validate height ")
isValid = false;
}
return isValid;
}
function executeCalculator(weight,height){
if(!validateInputs(weight,height))
return;
var result = weight / (height*height)
console.log(result);
if (result < 18.5) {
console.log("Your BMI is too low ")
} else if (result < 25) {
console.log("Your BMI is correct ")
} else if (result < 30) {
console.log("Your BMI is a little too high ")
} else if (result >= 30) {
console.log("Your BMI is too high ")
}
}
executeCalculator("",""); // Invalid
console.log("---")
executeCalculator("70",1.85);// Invalid
console.log("---")
executeCalculator(70,1.85);// Valid