Practice Set - Functions as Chunks of Reusable Code

by Chetak Patel

HTML

<p>There is one part to this practice set. This exercise is designed to give you practice creating a function from scratch, including accepting arguments and returning a value.  </p>
<p>You will write a function that calculates the average of numbers in a given array.  See the comments in the Javascript for more guidance. Your function will have to: <ol>
<li>iterate over the array that was passed in as an argument (think <i>for</i> loop)</li>
<li>add each value to a sum as it iterates</li>
<li>when the loop is complete, divide the sum by the length of the array</li>
</ol>
For this part, you may assume that the array contains only numbers. </p>
The output will appear here:
<ul>
<li>Average 1: <span id="average1"></span></li>
<li>Average 2: <span id="average2"></span></li>
<li>Average 3: <span id="average3"></span></li>
</ul>

<p>Remember that code can be awfully difficult to debug in JSFiddle. If you get frustrated trying to find a bug as you write your solution, you may want to copy this example to a local version on your computer to work it out, then paste it back in to JSFiddle.</p>

JavaScript

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});