I created a quick calculator in Javascript and I was wondering if there was a way to make the code look prettier or make it simpler. To me, it looks really cramped and messy and I'm not sure how change that.
function calc() {
var height = (document.getElementById('height').value) / 100;
var weight = document.getElementById('weight').value;
var output = document.getElementById('output');
var bmi = Math.round((weight / Math.pow(height, 2)) * 10) / 10;
var result = document.getElementById('result');
var text = "";
if (height != "" && weight != "") {
if (bmi != "NaN" && bmi != 0) {
if (bmi % 1 != 0) {
output.innerHTML = bmi;
} else {
output.innerHTML = bmi + ".0";
}
if (10 <= bmi && bmi < 14) {
text = "You are seriously underweight!";
} else if (15 <= bmi && bmi < 18.5) {
text = "You are slightly underweight.";
} else if (18.5 <= bmi && bmi < 25) {
text = "You are healthy!";
} else if (25 <= bmi && bmi < 30) {
text = "You are slightly overweight.";
} else if (30 <= bmi && bmi < 40) {
text = "You are obese!";
} else if (40 <= bmi && bmi < 50) {
text = "You are seriously obese!";
} else {
text = "You should be dead...";
}
result.innerHTML = text;
}
}
}
parseInt
orparseFloat
. What if someone enteredTall
as their height?"Tall" / 100
isNaN
, which you certainly don't want. \$\endgroup\$