In " The Ultimate JavaScript Mastery Series - Part 1", 14- Exercise 3- Error Handling,
I used the code provided by Mosh in the zip and shown in the video.
I put an array in the parameter, but the console returns “Invalid array”, how to fix this?
This is confusing!
try {
const numbers = [1, 2, 3, 4];
const count = countOccurrences(null, 1);
console.log(count);
}
catch (e) {
console.log(e.message);
}
function countOccurrences(array, searchElement) {
if (!Array.isArray(array))
throw new Error('Invalid array.');
return array.reduce((accumulator, current) => {
const occurrence = (current === searchElement) ? 1 : 0;
return accumulator + occurrence;
}, 0);
}
countOccurrences([1, 2], 'a');