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

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.