Search code examples
htmlbbedit

My code wont alert if the weight is too large or too small


After I get the weight I want the alert to be either "too large" or "too small" depending on the number The prompted user puts in. I can get the code to ask for a weight but after that nothing else alerts.

function calculateWeightInNewtons(mass) {

weight = mass * 9.8;
return weight;

if (weight > 500){
    alert("Weight is too big");
}
if (weight < 100){
    alert("weight is too small");
}



}

var massInKilograms = parseFloat(prompt("What is the object's mass in kilograms? "));
calculateWeightInNewtons(massInKilograms);

Solution

  • It's because you're returning from the function. The code below that isn't executed. If you need to return a value, make sure you do that after alerting the messages. But ideally, for a function to be cleaner it should only do one thing. So it's best to break down the functionality in different functions.

    function calculateWeightInNewtons(mass) {
      weight = mass * 9.8;
      return weight;
    }
    
    function alertWeight(weight) {
      if (weight > 500){
          alert("Weight is too big");
      }
      if (weight < 100){
          alert("weight is too small");
      }
    }
    
    var massInKilograms = parseFloat(prompt("What is the object's mass in kilograms? "));
    var weight = calculateWeightInNewtons(massInKilograms);
    alertWeight(weight);