Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Functions Return Values

Not checking for 'undefined'

      function arrayCounter (arr) {
        if (arr.isArray) {
            return arr.length;
        } else {
            return 0;
        }
      }

I'm getting an error saying that I'm not checking for undefined, but surely if I fed this function undefined it would return 0???

3 Answers

Andrew Shook
Andrew Shook
31,709 Points

I have answered this one before here.

Thanks Andrew, this ended up working after I realised my mistake:

      function arrayCounter (arr) {
        if (Array.isArray(arr)) {
            return arr.length;
        } else {
            return 0;
        }
      }
Steven Chin
Steven Chin
2,001 Points

Try this:

function arrayCounter(arr) {
   if ( ( arr.isArray ) && ( typeof(arr[arr.length]) != 'undefined' ) {
     return arr.length;
   }else {
     return 0;
   }
}

Ignore this, as ever the answer was my terrible attempt at using the isArray.

If anyone else happens to make the same mistake it should be called as Array.isArray(arr).