Practice Set: Parameter Validation
by jessupjs
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
var scoresArray4 = "this isn't an array";
var varRef4 = "scoresArray4";
//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",""]; // "" added (jj)
var varRef5 = "scoresArray5";
// hint: try converting each (or each non-numeric) array element to a number as you come to it
var scoresArray6 = [88, 73, "bob", 100];
var varRef6 = "scoresArray6";
// 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, varRef) {
var sum=0;
if (typeof arr !== "object") {
sum = "";
console.log("ERROR [" + varRef + "]: \"" + arr + "\" is not an array");
} else {
for (var i=0; i<arr.length; i++){
if (parseInt(arr[i])) {
sum+=parseInt(arr[i]);
} else {
console.log("ERROR [" + varRef + "]: the variable \"" + arr[i] + "\" was not evaluated");
}
}
}
return sum;
}
document.getElementById("sum4").innerHTML = calculateSum(scoresArray4, varRef4);
document.getElementById("sum5").innerHTML = calculateSum(scoresArray5, varRef5);
document.getElementById("sum6").innerHTML = calculateSum(scoresArray6, varRef6);