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

Robert Farese
Robert Farese
7,944 Points

I don't think I wrote this code in the most efficient way...

Here is how I answered this question...which came out correct but I can't imagine I wrote this in the most effective way. How can I consolidate all these if statements?

function arrayCounter (myArray) { if (typeof myArray === ‘string’){ return 0; } if (typeof myArray === ‘number’){ return 0; } if (typeof myArray === ‘undefined’){ return 0; } return myArray.length; }

2 Answers

Andrew Shook
Andrew Shook
31,709 Points

They didn't teach it during the course, but the most effective way to do this is to use isArray.

function arrayCounter( myArray){
    if( Array.isArray( myArray ) ){
        return myArray.length;
    }
    return 0;
}
Robert Farese
Robert Farese
7,944 Points

Hey Andrew! That's exactly what I was looking for. Thanks for your help!

Hi Robert,

You can try this:

function arrayCounter (myArray) {
    if(typeof myArray === 'string' || typeof myArray === 'number' || typeof myArray === 'undefined') {
        return 0;
    } else {
    return myArray.length;
    }
}
Robert Farese
Robert Farese
7,944 Points

Thanks Jeff! I had thought of using that operator...