Function Example 2



This example shows memory allocation when a function is called with a variable as the argument.

// Calling routine
function calcKM()
{
// declarations
var mph = 0;
var kph = 0;

// input
mph = document.getElementById("txtMPH").value;

// processing
kph = calcMphToKph(mph);    // function call with variable argument

// output
document.getElementById("txtKPH").value=kph;
}

// Function to convert miles per hour to kilometers per hour
function calcMphToKph(mph)
{
// declarations
var kph;
const conversionFactor = 1.609344;

// processing
kph = mph * conversionFactor;
kph = Math.round(kph * 100) / 100;

// output
return kph;
}


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


By the point the function call is encountered, the calling routine has a local variable named kph initialized to 0, and another local variable named mph that is assigned a value read from the form.


When calcMphToKph is called, memory is allocated for the parameter mph, the local variable kph, and the local constant conversionFactor.


The parameter mph in calcMphToKph receives its value from the argument in the calling routine, and the constant conversionFactor is assigned a value.


A value for the local variable kph is calculated by multiplying mph by conversionFactor.


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


After returning, the memory that was allocated for calcMphToKph is disposed of, and the returned value remains stored in kph.