1. Parameter Validation
When writing functions, it's essential to validate parameters to handle errors gracefully. This prevents unexpected behavior and makes your code more robust. For example, let's validate parameters in a function that calculates the mean score of students.
function getMeanScore(scores) {
// Check if the input is an array
if (!(scores instanceof Array)) {
return NaN; // Return NaN if the input is not an array
}
// Calculate the sum of scores
let sum = 0;
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
// Return the average score
return sum / scores.length;
}
// Test cases
console.log(getMeanScore(85)); // -> NaN
console.log(getMeanScore([80, 90])); // -> 85