Function Example 1



In this example, a function is called with a literal argument rather than a variable argument. Hence, it does not accept input from the user, but rather hard codes a weight.

// Calling routine
function calcWeight()
{
var kgs = 0;
kgs = lbsToKgs (225); // function call with literal argument
alert ("Your weight in kilograms is " + kgs);
}

// Function to convert pounds to kilograms
function lbsToKgs (pounds)
{
const conversionFactor = 0.453592;
var kilograms = conversionFactor * pounds;
return kilograms;
}


You can click on the lines above (starting with the variable declaration) for a popup explanation of parameter passing, or you can read the explanation that follows.


The calling routine has a local variable named kgs initialized to 0.


When lbsToKgs is called, memory is allocated for the function's parameter pounds, the local variable kilograms, and the local constant conversionFactor.


The function's parameter pounds receives its value from the argument in the calling routine, and conversionFactor is assigned a value.


A value for the local variable kilograms is calculated by multiplying pounds by conversionFactor.


When the return kilograms statement is reached the value is returned through the function call and assigned to the calling routine's local variable kgs.


After returning, the memory that was allocated for lbsToKgs is disposed of, and the returned value remains stored in kgs in the calling routine.