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

Gavin Murphy
Gavin Murphy
10,004 Points

Problem with challenge

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.

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(targetArray)  {
        if(typeof targetArray === 'undefined'){
          return 0;
        } else {
          return targetArray.length;
        }
      };

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

2 Answers

Alex Heil
Alex Heil
53,547 Points

hey Gavin Murphy , you're already on a good way. to solve the issue we need to look at the first part of your if-statement and compare it with the question:

the task is to return 0 for strings, numbers and undefined. now your if-statement checks for undefined, but what about the other 2 ? I guess you already know now what's missing and how to fix it, but of course I'll paste the whole code in here for reference:

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

hope that helps and have a nice day ;)

Gavin Murphy
Gavin Murphy
10,004 Points

Thank you very much Alex, I was pulling my hair out with that one lol

Sander Hofstede
Sander Hofstede
5,206 Points

My first impulse was to get the return in the function to check if the input is an array or not, and then work with the code. Tried typeof !== 'array' didn't work , but after some searching, i found out that doesn't work for some reason, but there is an isArray function within javascript MDN.

Basicly you put in Array.isArray(insertyourobj)

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