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

Karan kyanam
Karan kyanam
7,293 Points

Code challenge Javascript return functions

There is a code challenge in Function that deals with returning the arraylenght from a function, but i'm kind of stuck.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JavaScript Foundations: Functions</title>
    <style>
      html {
        background: #FAFAFA;
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <h1>JavaScript Foundations</h1>
    <h2>Functions: Return Values</h2>
    <script>

      function arrayCounter(array) {
        if(array.lenght === 'undefined'){
          return 'undefined';
        } else {
          return array.lenght;
        }

        arrayCounter([1, 3, 3]);

      }

    </script>
  </body>
</html>

4 Answers

Hi Karan,

The function must return the length of an array passed in or 0 if a 'string', 'number' or 'undefined' value is passed in.

For this problem, we need to check the argument's type to figure out what to return.

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

else
{
  // return the array's length
}

All that remains is to write the else portion that returns the array's length.

Karan kyanam
Karan kyanam
7,293 Points

Forgot the || or operator! Used commas instead. Thanks for the prompt reply!

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

Also you're not returning array.length correctly. I don't know if you've spotted that by now too. :-)

Karan kyanam
Karan kyanam
7,293 Points

I actually tried quite a few combinations cause I wasn't able to get through which contained array.lenght!

This was when I got really confused and the prompts made me change my code completely!

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

I also kept typing l e n g h t instead of l e n g t h.