Search code examples
javascriptarea

Area of the circle


So I created a .js file to calculate the area of a circle and calculateArea() needs to calculate it. The only thing that it does is the prompt(). What am I doing wrong?

function calculateArea(myRadius){
  var area = (myRadius * myRadius * Math.PI);
  return area;

  function MyArea(){
    calculateArea(myRadius);
    alert("A circle with a " + myRadius + 
          "centimeter radius has an area of " + area + 
          "centimeters. <br>" + myRadius + 
          "represents the number entered by the user <br>" + area +
          "represents circle area based on the user input.");  
  }      
}
var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:",0));
calculateArea(myRadius);

Solution

  • You need to keep function MyArea outside calculateArea and call calculateArea from within MyArea.

    Call MyArea function instead of calculateArea.

    Example Snippet:

    function calculateArea(myRadius) {
      return (myRadius * myRadius * Math.PI);
    }
    
    function MyArea() {
      var area = calculateArea(myRadius);
      alert("A circle with a " + myRadius + "centimeter radius has an area of " + area + "centimeters. <br>" + myRadius + "represents the number entered by the user <br>" + area + "represents circle area based on the user input.");
    
    
    }
    
    var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:", 0));
    MyArea(myRadius);

    PS: There are better ways to do this. Comment in case of questions.