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

Dirk Carney
Dirk Carney
6,111 Points

What is the best course of action for the Challenge Task in Stage 5: Functions?

Here is the code I put together, which is clearly not the solution:

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([]) {
        if (typeof arrayCounter === 'string') {
          return 0;  
        } else if (typeof arrayCounter === 'number') {
          return 0;
        } else if (typeof arrayCounter === 'undefined') {
          return 0;
        } else {
          return arrayCounter.length; 
        } 
     }


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

2 Answers

Robert Karlsson
Robert Karlsson
8,021 Points

It's a good solution but I would do it the other way around, check if its NOT an array. In Javascript, arrays are objects which means that you can compare it to "object".

I have made two solutions down below:

With understandable code:

 function arrayCounter(arr)
{
        if (typeof(arr) !== "object")
        {
          return 0;
        }
        else
        {
          return arr.length;
        }
}

With shorter code:

function arrayCounter(arr)
      {
        return ((typeof(arr) !== "object") ? 0 : arr.length);
      }

Hope this helps!