Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Foundations Functions Return Values

Pierre Poujade
Pierre Poujade
7,085 Points

This works in a REPL but doesn't pass the challenge

The challenge is "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."

      var arrayCounter = function (array) {
        if (array === undefined || !array.isArray()) {
          return 0;
        } else {
          return array.length;
        }
      }
Pierre Poujade
Pierre Poujade
7,085 Points

My bad, it doesn't work in a REPL.

3 Answers

This exercise had me for awhile too. It is suppose to emphasize "Returning Values", but the intention of the drill isn't clear when they are asking you to recall the if-else if exercises. Yes, i suppose its fair game, but it was easy for me to forget this as my study has been spotty. You must understand the use of 'typeof' keyword, as well. Might i refer you to the Mozilla documentation on JavaScript. click here If you do not see the answer there, try this code: ``` function arrayCounter(array) { if (typeof array === 'undefined') { return 0; } else if (typeof array === 'string') { return 0; } else if (typeof array === 'number') { return 0; } else { return array.length; }

} ``` I'll try this code again to make sure there aren't any errors.

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

} 

sorry...Markdown messed up cuz the triple quotes were on the same line as code.

Pierre Poujade
Pierre Poujade
7,085 Points

I ended up doing something like

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

thanks.