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

Geoff Sharpe
Geoff Sharpe
4,854 Points

Javascript function problem

I can't seem to build this function. Have tried a number of variations but still get it wrong. Any help with this would be great (I think I may be mixing up what the question is asking)

"Around line 17, create a function named 'arrayCounter' that takes in a parameter which is an array. The function must return the length of an array passed in or 0 if a 'string', 'number' or 'undefined' value is passed in."

4 Answers

Jimmy Hsu
Jimmy Hsu
6,511 Points

Same issue as from an earlier question:

All you need to do is check for the type with an if loop with 'typeof', then name of your parameter, then is equal to signs. There's multiple ways to do this, but it appears this is how they want you to do it.

Below is one solution.

function arrayCounter (array) {
  if (typeof array === 'undefined' ||typeof array === 'string'||typeof array === 'number') {
    return 0; 
  }
  return array.length;
}
function arrayCounter(array) {

 if(Array.isArray(array)) {
               return array.length;
      }
      else { return 0;}

      }
Jimmy Hsu
Jimmy Hsu
6,511 Points

Does that work through the treehouse challenge? It seems like it required to check for "undefined" specifically.

I used this function when i took the challenge and it works. It's a good solution because you make one test for the array and if is not an array you return 0.

Jimmy Hsu
Jimmy Hsu
6,511 Points

I agree with you on the method, but it seemed at the time the challenge was forcing me to use the phrase "undefined".

It is true the question is a bit weird and not logical from my point of view.