Functions that return values

by Chetak Patel

HTML

<h3>Open the Javascript console to see the output from this code</h3>
<p>Notice that I perform some <i>input validation</i> on line 2 to confirm that the function actually did receive two numbers as arguments before I add them. </p>
<p>In this case, my validation rule is that "if there are not two numeric arguments, don't do anything and return <code>null</code>.  I might code this differently if the valdiation rule was, say, "try to convert all parameters to numbers, and return the sum of those that are numeric."  </p>
<p>Be sure to read the comments in the Javascript code and the console for more information. </p>

JavaScript

var numberArray=[1,2,3,4,5], thisTotal=0,thisAverage=0;
// add elements of array together
 for(var i=0;i<numberArray.length;i++)
  {thisTotal+=numberArray[i];}
// calculate average
 thisAverage=(thisTotal/numberArray.length);
// display result
 alert(thisAverage)