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

Function Array Challenge

Could someone please explain what they are asking in this challenge:

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.''

<script>
...

</script>

???????????????

4 Answers

Hi Douglas,

The challenge wants you to use the typeof operator to check the type of the argument passed in. If it's one of the 3 types mentioned then you should return 0. Otherwise, you can assume it was an array (for the purposes of this challenge) that was passed in and you should return the length of that array.

You can check the type of a variable like this: typeof myVar; So you need to check that 3 times to see if it's equal to 'string' or 'number' or 'undefined'

function arrayCounter(myArray){
    if (typeof myArray == 'string') {
       return 0;
    }
    if (typeof myArray == 'number') {
       return 0;
    }
    if (typeof myArray == 'undefined') {
       return 0;
    }

    return myArray.length;
}

I think that's about what you would be expected to do based on what you've learned up to this point.

You can combine those using the logical OR || operator.

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

    return myArray.length;
}

There's a better way using the .isArray method but it's not taught in the course. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Jacob Cooper
Jacob Cooper
31,626 Points
function arrayCounter($array){
   if ($array.isArray){
      return $array.length;
   }else{
      //boolean false returns 0
      return false
   }
}

Hi Jacob,

This is beyond what the course teaches but it's fine to show better methods.

.isAray is a method which requires the object you're checking to be passed in.

You would use it like this:

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

Nice try but that doesn't work,

thanks anyway.

thanks that worked!! I never would of got that one on my own......thank you.