<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
"use strict";
// three arrays we'll calculate averages
var scoresArray1 = [87, 93, 69, 96, 77, 81];
var scoresArray2 = [56, 82, 71];
var scoresArray3 = [99, 97, 91, 89, 92];
// You'll write a function here called calculateAverage, which will
// accept one argument - the array, and return the average of the
// numbers in the array.
function calculateAverage(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum = sum + array [i];
}
var scoresArray1 = sum / array.length;
return scoresArray1
}
document.getElementById("average1").innerHTML = calculateAverage([87, 93, 69, 96, 77, 81])
document.getElementById("average2").innerHTML = calculateAverage([56, 82, 71])
document.getElementById("average3").innerHTML = calculateAverage([99, 97, 91, 89, 92])
//here we're calling your function on the three arrays and outputting the result
document.getElementById("average1").innerHTML = calculateAverage(scoresArray1);
document.getElementById("average2").innerHTML = calculateAverage(scoresArray2);
document.getElementById("average3").innerHTML = calculateAverage(scoresArray3);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.