Use function to calculate average in JavaScript

Description

The following code shows how to use function to calculate average.

Example


<html>
<head>
<script language="JavaScript">
function doCalcAvg(inpNum1, inpNum2, inpNum3, inpNum4)
{<!--  ww w.  ja v a  2s.  co  m-->
var ans;
ans = (Number(inpNum1) + Number(inpNum2) + Number(inpNum3) + Number(inpNum4)) / 4;
return (ans);
}

var inpNum1 = 1;
var inpNum2 = 2;
var inpNum3 = 3;
var inpNum4 = 4;
numAvg = doCalcAvg(inpNum1, inpNum2, inpNum3, inpNum4);
document.write("The average of the four numbers you entered is: " + numAvg);
</script>
</head>
</html>

Click to view the demo

The code above generates the following result.

Use function to calculate average in JavaScript