# Why returns invalid array for an array?

**URL:** <https://forum.codewithmosh.com/t/why-returns-invalid-array-for-an-array/14011>\
**Category:** JavaScript\
**Created:** [July 30, 2022, 2:21am UTC](https://forum.codewithmosh.com/t/why-returns-invalid-array-for-an-array/14011 "2022-07-30T02:21:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![achantt](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/achantt/32/4215_2.png) [@achantt](https://forum.codewithmosh.com/u/achantt)\
**Post date:** [July 30, 2022, 2:21am UTC](https://forum.codewithmosh.com/t/why-returns-invalid-array-for-an-array/14011/1 "2022-07-30T02:21:10Z")

</div>

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!

```auto
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');

```

---

<div class="post-metadata">

**Author:** ![GandalfTheBlack](https://avatars.discourse-cdn.com/v4/letter/g/9dc877/32.png) [@GandalfTheBlack](https://forum.codewithmosh.com/u/GandalfTheBlack)\
**Post date:** [July 30, 2022, 3:09am UTC](https://forum.codewithmosh.com/t/why-returns-invalid-array-for-an-array/14011/2 "2022-07-30T03:09:32Z")

</div>

When you run the code above, it’ll execute the try catch before it gets to your function call, and since you called the function with null on line 3, it threw the error. Throwing an error stops the program so it never gets to the function call on the last line.

---

<div class="post-metadata">

**Author:** ![achantt](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/achantt/32/4215_2.png) [@achantt](https://forum.codewithmosh.com/u/achantt)\
**Post date:** [July 30, 2022, 6:21am UTC](https://forum.codewithmosh.com/t/why-returns-invalid-array-for-an-array/14011/3 "2022-07-30T06:21:16Z")

</div>

I changed the `null` to an array , still returns “Invalid array”

```auto
try {
  const numbers = [1, 2, 3, 4]; 
  const count = countOccurrences([1,2,3], 1); 
  console.log(count); 
}
catch (e) {
  console.log(e.message);
}

```
