JSFiddle - React, Tailwind, and code Playground
by DustyWhite
HTML
<p>There is one part to this practice set. This exercise is designed to give you practice validating input, in this case, arguments to a function. </p>
<p>
Our function, calculateSum(), adds the numbers in the array and returns the sum. We've created three "arrays" of input data to for our function, each of which will fail in some way if your function doesn't include code to deal with input of the 'wrong' type. </p>
<p>
A better solution would be to check for the kind of error condition that each example contains. To do this, you'll want to tackle the cases presented in the sample arrays one at a time. You will modify the calculateSum() function to handle each of these cases. With each change, your code will become more robust (specifically, more tolerant of unexpected input). See the comments in the code for some suggestions.
</p>
The output will appear here:
<ul>
<li>Sum 4: <span id="sum4"></span></li>
<li>Sum 5: <span id="sum5"></span></li>
<li>Sum 6: <span id="sum6"></span></li>
</ul>
<p>
Finally, one test we didn't do was for the case where nothing is passed in as an argument. If you can, modify the code you wrote for the scoresArray1 case to also hande the case in which the input is undefined.
</p>
JavaScript
var scoresArray1 = [1,2,3];
var scoresArray2 = [56, 82, 71];
var scoresArray3 = [99, 97, 91, 89, 92];
function calculateSum(arr){
var sum=0, num;
for (var i=0; i<arr.length; i++){
num = parseInt(arr[i]);
}
/* sum=0;
for (var i=0; i<arr.length; i++){
} */
return sum;
}
document.getElementById("sum4").innerHTML = calculateSum(scoresArray1);
document.getElementById("sum5").innerHTML = calculateSum(scoresArray2);
document.getElementById("sum6").innerHTML = calculateSum(scoresArray3);