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

Function output 0 instead of array length

Why does this function return 0 for an array instead of the length of the array?

  function arrayCounter (a) {
     if (typeof a === 'undefined', 'string', 'number'){
       return 0;
     }
     return a.length;
  }

3 Answers

You want to compare typeof a to 'undefined' or 'string' or 'number', so you would need to use the or operator: ||

See below:

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

Hey Max,

Hopefully I can help. First, I think while that if statement seems to work it, I do not think it really does. Maybe using the or operator to check your typeof on a would work. JS does not allow for the typeof a === "string", "undefined" syntax. For example:

function arrayCounter (a) {
if (typeof a === "undefined" || typeof a === "string" || typeof a === "number") {
return 0;
}
return a.length;
}

I hope this helps!

Matt

Thank you - the "||" provided the solution for the problem!