Home > Software engineering >  [INQUIRY ]JavaScript - Variable Initilization
[INQUIRY ]JavaScript - Variable Initilization

Time:10-16

function calculateArea(r){
  var area;
  if (r<=0){
    return 0;
  } else {
    area=Math.PI*r*r; 
    return area; 
  }
}

var radius = 5.2; 
var theArea=calculateArea(radius);
console.log("Area = "   theArea); 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

New here, please let me know if I have posted incorrectly.

If the initialization of a variable is a function. Does the function execute automatically? For instance, see my code below. I get the desired output in the console log. Had I not included this function in the variable, would it have still ran?

   function calculateArea(r){
  var area;
  if (r<=0){
    return 0;
  } else {
    area=Math.PI*r*r; 
    return area; 
  }
}

var radius = 5.2; 
var theArea=calculateArea(radius);
console.log("Area = "   theArea); 

EDIT: Think I've got my head wrapped around this not. Thank you all!

CodePudding user response:

if you call it without any arguments

calculateArea()

r will be undefined, leading to Math.PI * r * r = number * undefined = NaN

and if you never used this

var theArea=calculateArea(radius);

then the function won't be executed automatically

CodePudding user response:

No, defining a function doesn't run it automatically. (After all, if it requires an argument, like r in your case, what would that r be?)

You will need to call the function (calculateArea(1)) for it to be run, but you don't need to assign the return value to a variable (area = calculateArea(1)) for that to happen.

  • Related