Practice Set: Parameter Validation
by jhu26
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 scoresArray4 case to also hande the case in which the input is undefined.
</p>
JavaScript
// the sample input data we'll be validating
"use strict";
var scoresArray4 = "this isn't an array";
//hint: try testing to see if this is actually an array before doing anything else in the function. Remember that 'typeof' works for simple data types, but [object].constructor.name will tell you the type of many objects. We show this in video 4.4 (towards the end).
var scoresArray5 = [76, 83, "90"];
// hint: try converting each (or each non-numeric) array element to a number as you come to it
var scoresArray6 = [88, 73, "bob", 100];
// hint: while you're converting all array elements to numbers, use a conditional to check to see if it worked before adding the value to the sum
// function calculateSum() is here
// You will modify this function so that none of the above cases
// "break" the code. If the sum simply can't be done (as in scoresArray4),
// return the value 'null' or nothing at all, and write an error to the console.
// Otherwise, if a sum can still be calculated, return that
function calculateSum(arr){
var sum=0;
for (var i=0; i<arr.length; i++){
if(typeof arr[i] == "string" && parseInt(arr[i] != "NaN")){
console.log("String not NaN: " + arr[i] );
console.log("sum before = " + sum);
sum += parseInt(arr[i]);
console.log("sum after = " + sum);
} else {
//console.log("Isn't String");
sum+=arr[i];
}
}
return sum;
}
document.getElementById("sum4").innerHTML = calculateSum(scoresArray4);
document.getElementById("sum5").innerHTML = calculateSum(scoresArray5);
document.getElementById("sum6").innerHTML = calculateSum(scoresArray6);