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

Dan Neumann
PLUS
Dan Neumann
Courses Plus Student 10,318 Points

Array function question in Javascript Foundations

I have no idea how to answer the following question with what I've learned so far. Please help. The question is:

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.

I gave this for an answer but it was't right.

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>
      var sample1 = new array();
      function arrayCounter(sample1) {
        if (sample1.length > 1) {
        return array1.length;
        } else return 0;
      }  

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

2 Answers

You could use

if(Array.isArray(sample1) )

{ return sample1.length; }

else {return 0;)

OR you could use a faster method of checking array

if (sample1 instanceof Array) ...

Also in your code, the return array1.length;. The array1 is not defined, it should be sample1.length;

Here is the working code

var sample1 = []; var arrayCounter = function (param) { if(Array.isArray(param) ) { return param.length; }

else { return 0; } }

arrayCounter(sample1);

Andrew Youngwerth
Andrew Youngwerth
10,188 Points

Hello Dan, The issue with your current code is that .length works with other javascript types as well as arrays. The way I would do it would be to first use the javascript isArray method. For example

if (Array.isArray(sample1)) {
    return sample1.length
} else {
    return 0
}