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

Brian Wynn
Brian Wynn
10,694 Points

How do I define an array as an argument in a function?

In the associated challenge for Return Values within the JavaScript fundamentals course, there is a questions that asks to return the length of an array as defined by the function arrayCounter. If an array is passed through, the length is provided. If any other argument (number, string, etc... is passed through the function, a return value of '0' is established. How do I set a function that identifies the argument solely as an array? I re-watched the videos and could not find the answer.

My code as is looks like this:

function arrayCounter(a) {
if (typeof a === 'undefined') {
return 0;
}
return a.length;
};

I think this should do the trick!

function arrayCounter(a) {
if (typeof a === 'object') {
return a.length;
}
return 0;
};

In JS an array is considered to be an object. As far as I know this is the easiest way to to check for arrays, but there are certainly others.

Brian Wynn
Brian Wynn
10,694 Points

That was it! Much appreciated, that was driving me crazy, now it makes more sense. Thanks :)

1 Answer

Hi Brian,

I fixed your code formatting for you. This thread will show you how to post code: https://teamtreehouse.com/forum/posting-code-to-the-forum

You're pretty close with your solution.

You're correctly checking if the type of the variable passed in is 'undefined' and returning 0 if it is. The challenge also wants you to specifically check if the type is a 'string' or 'number' as well and to return 0 for those types too.

So all you need to add is 2 more if blocks like the one you already have but check instead for the other 2 types.